【发布时间】:2020-09-18 14:40:05
【问题描述】:
我正在开发一个编译时包装库,偶然发现了从给定类型中提取模板参数类型的问题。
情况如下。我有一个不可更改的类R:
template <class T>
class R {};
我还有一个不可更改的main函数:
int main()
{
auto r = new R<int>();
// Function that knows the type of 'r'
create_obj<decltype(r)>();
delete r;
return 0;
}
create_obj 函数是我正在研究的函数。出于可视化的目的,我会这样写:
template< class C >
void create_obj()
{
// Print the type of the function (Output: R<int>*)
std::cout << boost::typeindex::type_id<C>().pretty_name() << std::endl;
}
问题是我需要从create_obj函数访问R类的int模板参数类型。
伪代码:
template<
template < class T >
class C<T>
>
void create_obj()
{
// Print the type of the function (Output: int)
std::cout << boost::typeindex::type_id<T>().pretty_name() << std::endl;
}
有可能吗?我正在浏览 C++ 文档,但找不到任何方法从类定义中“分离”模板参数类型。
【问题讨论】:
-
create_obj实际上应该引用r还是什么?目前它不接受任何参数并且不返回任何内容,因此您想要它做什么并不完全清楚。 -
this 你在找什么吗?
-
@NathanOliver 我已经尝试过
std::declval,但是这里说明为类R的指定类型C可能是一个非常复杂的类,不容易实例化。 -
@Useless 这正是没有引用,没有对象,什么都不能创建的关键。这个想法只是从已经存在的类型中提取一个类型。
标签: c++ templates template-meta-programming