I wonder if anyone knows why the following two pieces of code behave very differently. I can understand why the second one doesn't work, but why does the first one work? At the same place int x = gc.f();
the template should get instantiated so the same error would occur, but why actually there is no error?
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() {
}
output
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() {
}
compiler error
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>’