2010-06-14 77 views
3

我試圖編譯下面基於模板的代碼在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模板內的類型。任何幫助,高度讚賞。

回答

5

由於T3取決於模板參數,編譯器無法知道肯定有什麼T3::xType將引用(可能在每個實例T2<r>取決於實際類型r )。

要告訴編譯器T3::xType將是一個類型,你需要添加typename關鍵字:

typedef typename T3::xType xType; 
+0

thanx很多。這工作。 – 2010-06-14 15:33:06

3

在你的模板類嘗試

typedef typename T3::xType xType; 
2

錯誤消息告訴你,正是你需要做什麼:類型之前添加typename

typedef typename T3::xType xType;

你需要這個,如果有,可以被視爲一個變量或類型的標識符,編譯器將把它作爲一個變量,這是發生了什麼事在這種情況下的原因。爲了讓編譯器知道它實際上是一種使用typename關鍵字的類型。