巢狀的類別樣板
範本可定義類別或類別樣板中,在此情況下它們稱為成員樣板。 成員樣板的類別稱為 「 巢狀的類別樣板 」。 成員樣板函式,會討論成員函式樣板。
巢狀的類別樣板宣告為外部的類別範圍內的類別樣板。 它們可以在裡面或外面封入類別定義。
範例
下列程式碼會示範在一般的類別內的巢狀的類別範本。
// nested_class_template1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class X
{
template <class T>
struct Y
{
T m_t;
Y(T t): m_t(t) { }
};
Y<int> yInt;
Y<char> 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();
}
巢狀的類別樣板會定義其封入類別之外,它們必須是以同時類別樣板 (如果它們是在類別樣板的成員) 的範本參數與成員樣板的樣板參數檔案名稱為開頭。
// nested_class_template2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
template <class T>
class X
{
template <class U> class Y
{
U* u;
public:
Y();
U& Value();
void print();
~Y();
};
Y<int> y;
public:
X(T t) { y.Value() = t; }
void print() { y.print(); }
};
template <class T>
template <class U>
X<T>::Y<U>::Y()
{
cout << "X<T>::Y<U>::Y()" << endl;
u = new U();
}
template <class T>
template <class U>
U& X<T>::Y<U>::Value()
{
return *u;
}
template <class T>
template <class U>
void X<T>::Y<U>::print()
{
cout << this->Value() << endl;
}
template <class T>
template <class U>
X<T>::Y<U>::~Y()
{
cout << "X<T>::Y<U>::~Y()" << endl;
delete u;
}
int main()
{
X<int>* xi = new X<int>(10);
X<char>* xc = new X<char>('c');
xi->print();
xc->print();
delete xi;
delete xc;
}
Output
1 a
Output
X<T>::Y<U>::Y()
X<T>::Y<U>::Y()
10
99
X<T>::Y<U>::~Y()
X<T>::Y<U>::~Y()
不允許本機的類別可以有成員樣板。