提取模板类中的类型以用于其他模板
extracting the type in a template class for use in other templates
如何从类中提取模板类型:
例如,我有一个类:
template <typename T, typename T2 = def>
class A
{
typedef T type;
typedef T2 type2;
//other stuff
}
我想在其他模板中使用type2
:
template <typename G>
foo(A<G> a)
{
//This doesn't work:
std::vector<a::type2> vec;
//Neither does this:
std::vector<a->type2> vec;
//or this:
std::vector<typename a::type2> vec;
}
那么,我如何计算实例a
的type2
是什么呢(a
是否可以为type2
指定一个非默认值)?
这应该有效:
std::vector<typename A<G>::type2> vec;
原因:std::vector
需要一个完整类型作为其参数,只有A
是template
,但A<G>
变成了完整类型。从你的例子中,我提到了A<G>
,但它可以是A<int>
,A<char>
任何东西。
如果您的编译器支持它,您可以使用decltype
功能来命名对象的类型。
template <typename G>
void foo(A<G> a)
{
std::vector<typename decltype(a)::type2> vec;
}
在本例中,decltype(a)
是类型A<G>
。
相关文章:
- 程序没有问 3 个问题,而是将我对第一个问题的回答用于其他两个问题
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- 将其他函数中的变量用于主函数C++
- 在Visual Studio中包括用于其他PC的库
- 在 Eclipse 中漂亮的打印C++适用于某些项目,而不适用于其他项目
- 在一个类中向向量添加元素不适用于其他类
- 访问void函数中的变量以用于其他函数?C++
- 现代C和C :可以将一个定义的结构用于其他声明的结构
- 如果您称为destructor并将分配的内存再次用于其他对象,会发生什么
- 如何使C枚举类型可用于其他语言
- 提取模板类中的类型以用于其他模板
- 函数模板可用于本地lambda,但不能用于其他函数
- Gradle C(本机)任务输出文件(用于其他任务/项目)
- ShellExecute 不适用于其他计算机
- C++-如何使显式导入的DLL函数可用于其他类
- 如何正确地将std::函数用于其他数据类型(在优先级队列中)
- 使动态初始化的变量可用于其他.cpp文件
- c++中的Curl_easy_perform会停止用于其他用途的计时器
- 将 main 中的变量值更改为可用于其他函数 (c++)
- 模板中的构造函数不同:一个用于字符串,另一个用于其他任何东西