c++ - 在特定情况下使用 C++ 模板将整数映射到类型失败

标签 c++ templates

我正在尝试在 VC++ 2005 中编译以下基于模板的代码。

    #include <iostream>
using namespace std;


/*
 * T is a template which maps an integer to a specific type.
 * The mapping happens through partial template specialization.
 * In the following T<1> is mapped to char, T<2> is mapped to long
 * and T<3> is mapped to float using partial template specializations
 */
template <int x>
struct T
{
public:
};

template<>
struct T<1>
{
public:
    typedef char xType;
};


template<>
struct T<2>
{
public:
    typedef long xType;
};

template<>
struct T<3>
{
public:
    typedef float xType;
};

// We can easily access the specific xType for a specific T<N>
typedef T<3>::xType x3Type;

/*!
 * In the following we are attempting to use T<N> inside another
 * template class T2<R>
 */

template<int r>
struct T2
{
    //We can map T<r> to some other type T3
    typedef T<r> T3;
    // The following line fails
    typedef T3::xType xType;
};

int main()
{
    T<1>::xType a1;
    cout << typeid(a1).name() << endl;
    T<2>::xType a2;
    cout << typeid(a2).name() << endl;
    T<3>::xType a3;
    cout << typeid(a3).name() << endl;
    return 0;
}

代码中有一行无法编译:

typedef T3::xType xType;

如果我删除这一行,编译会正常进行,结果是:

char
long
float

如果我保留这一行,则会观察到编译错误。

main.cpp(53) : warning C4346: 'T<x>::xType' : dependent name is not a type
    prefix with 'typename' to indicate a type
    main.cpp(54) : see reference to class template instantiation 'T2<r>' being compiled
main.cpp(53) : error C2146: syntax error : missing ';' before identifier 'xType'
main.cpp(53) : error C4430: missing type specifier - int assumed. Note: C++ does not    support default-int

我无法弄清楚如何确保 T::xType 可以被视为 T2 模板中的一种类型。非常感谢任何帮助。

最佳答案

T3在你的模板类中取决于模板参数,编译器无法确定是什么 T3::xType将引用(这可能取决于每个实例化中的实际类型 r T2<r>)。

告诉编译器 T3::xType将是一种类型,您需要添加 typename关键词:

typedef typename T3::xType xType;

关于c++ - 在特定情况下使用 C++ 模板将整数映射到类型失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3037846/

相关文章:

c++ - 使用迭代器时出现编译错误 : "error: ‘...::iterator’ has no member named '...' "

c++ - 不支持 VARIADIC 的宏自动注入(inject)参数

c++ - char* 不应该隐式转换为 std::string 吗?

c++ - 哪个是 G++ 4.4.1 默认分配器?

c++ - 如何从模板化类方法返回依赖类型?

c++ - 标志如何在 C 中工作?

c++ - 在软件渲染器中模仿顶点/片段着色器的设计模式是什么?

c++ - 使用模板相关类型在 C++ 中重载运算符 "<<"

html - 我如何解决 should trim empty<i> aptana studio 中的警告?

C++ - 为模板类专门化成员函数