我试图在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;
}
Run Code Online (Sandbox Code Playgroud)
代码中有一个特殊的行不能编译:
typedef T3::xType xType;
Run Code Online (Sandbox Code Playgroud)
如果我删除这一行,编译就可以了,结果是:
char
long
float
Run Code Online (Sandbox Code Playgroud)
如果我保留此行,则会观察到编译错误.
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
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何确保T :: xType可以被视为T2模板中的类型.任何帮助都非常感谢.
由于T3
在模板类中依赖于模板参数,因此编译器无法确定T3::xType
将引用什么(可能取决于r
每个实例化中的实际类型T2<r>
).
要告诉编译器T3::xType
将是一个类型,您需要添加typename
关键字:
typedef typename T3::xType xType;
Run Code Online (Sandbox Code Playgroud)