为什么我不能在C++中使用模板化的typedef?

pet*_*ohn 0 c++ templates 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));
}
Run Code Online (Sandbox Code Playgroud)

为什么不编译?它抱怨该B::f()方法的部分.它似乎没有认识到类中的typedef A<T>.如果我改为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
Run Code Online (Sandbox Code Playgroud)

我甚至尝试了另一种方式,但它仍然无效:

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

如何使这些代码工作?

Tug*_*tes 5

A<T>::PairType解析struct B模板时编译器不知道这是一种类型.知道是否A<T>::PairType是类型的唯一方法是实例化两个模板,直到主函数才会实现.

明确告诉编译器它是这样的:

void f(typename A<T>::PairType p)
Run Code Online (Sandbox Code Playgroud)