我想知道为什么以下两段代码表现非常不同。我可以理解第二个不起作用的原因,但为什么第一个可以工作呢?在相同的地方int x = gc.f();
模板应该被实例化,所以会发生相同的错误,但为什么实际上没有错误呢?
a.cpp
#include <iostream>
using namespace std;
template <typename T>
struct A {
struct B {
};
};
template <typename T>
struct C {
typedef A<C<T> > D;
int f() {
typename D::B p;
return 0;
}
};
C<float> gc;
int x = gc.f();
template <typename T>
struct A<C<T> > {
struct B {
B() {
cout << "B::B()" << endl;
}
~B() {
cout << "B::~B()" << endl;
}
};
};
int main() {
}
输出
B::B()
B::~B()
and
a2.cpp
#include <iostream>
using namespace std;
template <typename T>
struct A {
struct B {
};
};
struct C {
typedef A<C> D;
int f() {
D::B p;
return 0;
}
};
C gc;
int x = gc.f();
template <>
struct A<C> {
struct B {
B() {
cout << "B::B()" << endl;
}
~B() {
cout << "B::~B()" << endl;
}
};
};
int main() {
}
编译器错误
a2.cpp:24: error: specialization of ‘A<C>’ after instantiation
a2.cpp:24: error: redefinition of ‘struct A<C>’
a2.cpp:6: error: previous definition of ‘struct A<C>’