提取模板类中的类型以用于其他模板

extracting the type in a template class for use in other templates

本文关键字:用于 其他 类型 提取      更新时间:2023-10-16

如何从类中提取模板类型:

例如,我有一个类:

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;
}

那么,我如何计算实例atype2是什么呢(a是否可以为type2指定一个非默认值)?

这应该有效:

std::vector<typename A<G>::type2> vec;

原因std::vector需要一个完整类型作为其参数,只有Atemplate,但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>