2011-03-06 81 views
0

考慮下面的程序:爲什麼我不能在C++中使用模板化的typedefs?

#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 2011-03-06 16:20:25

+0

可能的重複[Where to put the「template」and「typename 「在依賴名稱](http://stackoverflow.com/questions/610245/where-to-put-the-template-and-typename-on-dependent-names) – fredoverflow 2011-03-06 16:31:59

回答

5

編譯器不知道A<T>::PairType是解析struct B模板時的一種類型。知道A<T>::PairType是否是一種類型的唯一方法是實例化兩個模板,直到您的主函數纔會發生。

告訴編譯器明確,它是如此:成員模板函數的

void f(typename A<T>::PairType p) 
相關問題