2011-03-06 3 views
0

다음 프로그램을 고려하십시오.C++에서 템플릿 typedef를 사용할 수없는 이유는 무엇입니까?

#include <iostream> 
#include <algorithm> 

using namespace std; 

template<class T> 
struct A { 
    typedef pair<T, T> PairType; 
}; 

template<class T> 
struct B { 
    void f(A<T>::PairType p) { 
     cout << "f(" << p.first << ", " << p.second << ")" << endl; 
    } 
    void g(pair<T, T> p) { 
     cout <<"g(" << p.first << ", " << p.second << ")" << endl; 
    } 
}; 

int main() { 
    B<int> b; 
    b.f(make_pair(1, 2)); 
    b.g(make_pair(1, 2)); 
} 

왜 컴파일되지 않습니까? 그것은 B::f() 메소드를 사용하는 부분에 대해 불평합니다. A<T> 클래스의 typedef를 인식하지 못하는 것 같습니다. T을 구체적인 유형으로 변경하면 작동합니다. 전체 오류 메시지는 다음과 같습니다.

g++ -DNDEBUG -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.cpp" 
../main.cpp:13: error: ‘template<class T> struct A’ used without template parameters 
../main.cpp:13: error: expected ‘,’ or ‘...’ before ‘p’ 
../main.cpp: In member function ‘void B<T>::f(int)’: 
../main.cpp:14: error: ‘p’ was not declared in this scope 
../main.cpp: In function ‘int main()’: 
../main.cpp:23: error: no matching function for call to ‘B<int>::f(std::pair<int, int>)’ 
../main.cpp:13: note: candidates are: void B<T>::f(int) [with T = int] 
make: *** [main.o] Error 1 

다른 방법으로 시도해 보았지만 여전히 작동하지 않았습니다.

void f(A::PairType<T> p) { 
    cout << "f(" << p.first << ", " << p.second << ")" << endl; 
} 

어떻게 이러한 코드를 작동시킬 수 있습니까?

+0

가능한 중복. 왜이 컴파일되지 않습니다?] (http://stackoverflow.com/questions/5204004/member-template-function-why-doesnt-this-compile) – Jon

+0

가능한 복제본 [템플릿 및 "typename "종속 이름] (http://stackoverflow.com/questions/610245/where-to-put-the-template-and-typename-on-dependent-names) – fredoverflow

답변

5

struct B 템플릿을 구문 분석 할 때 컴파일러에서 A<T>::PairType이 형식이라는 것을 알지 못합니다. A<T>::PairType이 유형인지 여부를 알 수있는 유일한 방법은 두 템플리트 모두를 인스턴스화하는 것이며, 이는 주 기능이 될 때까지는 발생하지 않습니다.

는 너무 것을 명시 적으로 컴파일러를주기 : [회원 템플릿 기능의

void f(typename A<T>::PairType p) 
관련 문제