다음을 통해 공유


중첩 된 클래스 템플릿

템플릿 클래스 또는 템플릿 클래스를 정의할 수 있습니다, 그리고 경우 들에 구성원 템플릿이라고 합니다.클래스는 멤버 템플릿은 중첩된 클래스 서식 파일 이라고 합니다.함수는 멤버 템플릿을 설명 되어에서 멤버 함수 템플릿은.

중첩 된 클래스 템플릿 클래스 템플릿 내부 범위에서 외부 클래스의 이름으로 선언 됩니다.안쪽 또는 바깥쪽 클래스 외부에 정의할 수 있습니다.

예제

다음 코드는 일반 클래스 안에 중첩된 클래스 템플릿을 보여 줍니다.

// 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()

지역 클래스는 멤버 템플릿을 가질 수 없습니다.

참고 항목

참조

클래스 템플릿

멤버 함수 템플릿