[英]Why can't I use templated typedefs in C++?
考虑以下程序:
#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;
}
如何使这样的代码起作用?
解析struct B
模板时,编译器不知道A<T>::PairType
是一种类型。 知道A<T>::PairType
是否为类型的唯一方法是实例化这两个模板,直到您的主函数才发生。
明确告诉编译器是这样的:
void f(typename A<T>::PairType p)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.