2010-06-14 5 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::xType가 각 인스턴스 T2<r>에 실제의 형태 r에 따라 수 (참조 될지 확실히 알 수 없습니다 수).

T3::xType이 유형을 될 것입니다 컴파일러에게, 당신은 typename 키워드를 추가해야합니다 유형 전에 typename을 추가

typedef typename T3::xType xType; 
+0

많이 있습니다. 이 작품. –

3

는 템플릿 클래스에서 T3 때문에

typedef typename T3::xType xType; 
2

오류 메시지가 정확히 무엇을해야하는지 알려줍니다.

typedef typename T3::xType xType;

이 변수 또는 유형으로 처리 할 수있는 식별자가 있다면, 컴파일러는이 경우에 무슨 일이 일어나고있는 변수로 취급하는 것입니다 필요한 이유. 컴파일러가 실제로 유형임을 알리기 위해 typename 키워드를 사용합니다.