다음을 통해 공유


멤버 함수 템플릿

멤버 템플릿이라는 용어는 멤버 함수 템플릿과 중첩된 클래스 템플릿을 둘 다 나타냅니다. 멤버 함수 템플릿은 클래스 또는 클래스 템플릿의 멤버인 함수 템플릿입니다.

멤버 함수는 여러 컨텍스트에서 함수 템플릿이 될 수 있습니다. 클래스 템플릿의 모든 함수는 제네릭이지만 멤버 템플릿 또는 멤버 함수 템플릿이라고 하는 것은 아닙니다. 이러한 멤버 함수가 자체 템플릿 인수를 사용하는 경우 멤버 함수 템플릿으로 간주됩니다.

예: 멤버 함수 템플릿 선언

템플릿이 아닌 클래스 또는 클래스 템플릿의 멤버 함수 템플릿은 해당 템플릿 매개 변수를 사용하여 함수 템플릿으로 선언됩니다.

// member_function_templates.cpp
struct X
{
   template <class T> void mf(T* t) {}
};

int main()
{
   int i;
   X* x = new X();
   x->mf(&i);
}

예: 클래스 템플릿의 멤버 함수 템플릿

다음 예제에서는 클래스 템플릿의 멤버 함수 템플릿을 보여줍니다.

// member_function_templates2.cpp
template<typename T>
class X
{
public:
   template<typename U>
   void mf(const U &u)
   {
   }
};

int main()
{
}

예: 클래스 외부의 멤버 템플릿 정의

// defining_member_templates_outside_class.cpp
template<typename T>
class X
{
public:
   template<typename U>
   void mf(const U &u);
};

template<typename T> template <typename U>
void X<T>::mf(const U &u)
{
}

int main()
{
}

예: 템플릿 기반 사용자 정의 변환

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

멤버 함수 템플릿은 가상 함수일 수 없습니다. 또한 기본 클래스 가상 함수와 동일한 이름으로 선언된 경우 기본 클래스에서 가상 함수를 재정의할 수 없습니다.

다음 예제에서는 템플릿 기반 사용자 정의 변환을 보여줍니다.

// templated_user_defined_conversions.cpp
template <class T>
struct S
{
   template <class U> operator S<U>()
   {
      return S<U>();
   }
};

int main()
{
   S<int> s1;
   S<long> s2 = s1;  // Convert s1 using UDC and copy constructs S<long>.
}

참고 항목

함수 템플릿