Templates can be defined within classes or class templates, in which case they are referred to as member templates. Member templates that are classes are referred to as nested class templates. Member templates that are functions are discussed in .
Nested class templates are declared as class templates inside the scope of the outer class. They can be defined inside or outside of the enclosing class.
The following code demonstrates a nested class template inside an ordinary class.
// nested_class_template1.cpp// compile with: /EHsc#includeusing namespace std;class X{ template struct Y { T m_t; Y(T t): m_t(t) { } }; Y yInt; Y yChar;public: X(int i, char c) : yInt(i), yChar(c) { } void print() { cout << yInt.m_t << " " << yChar.m_t << endl; }};int main(){ X x(1, 'a'); x.print();}
When nested class templates are defined outside of their enclosing class, they must be prefaced by the template parameters for both the class template (if they are members of a class template) and template parameters for the member template.
// nested_class_template2.cpp// compile with: /EHsc#includeusing namespace std;template class X{ template class Y { U* u; public: Y(); U& Value(); void print(); ~Y(); }; Y y;public: X(T t) { y.Value() = t; } void print() { y.print(); }};template template X ::Y ::Y(){ cout << "X ::Y ::Y()" << endl; u = new U();}template template U& X ::Y ::Value(){ return *u;}template template void X ::Y ::print(){ cout << this->Value() << endl;}template template X ::Y ::~Y(){ cout << "X ::Y ::~Y()" << endl; delete u;}int main(){ X * xi = new X (10); X * xc = new X ('c'); xi->print(); xc->print(); delete xi; delete xc;}
1 a
X::Y ::Y()X ::Y ::Y()1099X ::Y ::~Y()X ::Y ::~Y()
Local classes are not allowed to have member templates.