2009-11-15 6 views

답변

3

해당 유형의 메소드를 전문화 할 수 있습니다. 예 :

template<typename T> 
struct TemplatedClass 
{ 
    std::string methodA() {return "T methodA";} 

    std::string methodB() {return "T methodB";} 
    std::string methodC() {return "T methodC";} 
}; 

// Specialise methodA for int. 

template<> 
std::string TemplatedClass<int>::methodA() 
{ 
    return "int methodA"; 
} 
4

이 특정 유형에 대해 partial (or full) specialization을 만들어야합니다.

+5

전체 유형을 전문화해야하지만, 일부만 멤버 함수를 특수화 할 수는 없습니다. 이것은 해답에 함축되어 있지만 오해를 불러 일으킬 수 있습니다. –

+0

기본 클래스를 사용하여 기본 구현을 제공하고이 기본 클래스의 생성자/소멸자를 사용하지 않도록 보호함으로써이 제한을 극복 할 수 있습니다. –

2

티모의 대답은 컴파일러가 자동으로 특수 유형으로 기본 형식에서 멤버 함수를 복사하지 않습니다 즉, 당신은 전체 클래스를 전문으로 할 수 있습니다.

다른 모든 것을 다시 만들지 않고 클래스의 특정 메서드를 특수화하려면 좀 더 복잡합니다.

template<typename T> struct TypeHolder { }; 

template<typename T> class TemplateBase { 
public: 
    void methodInterface() { 
     methodImplementation(TypeHolder<T>); 
    } 
    void anotherMethod() { 
     // implementation for a function that does not 
     // need to be specialized 
    } 
private: 
    void methodImplementation(TypeHolder<int>) { 
     // implementation for int type 
    } 
    void methodImplementation(TypeHolder<float>) { 
     // implementation for float type 
    } 
}; 

컴파일러는 methodInterface에 해당 methodImplementation 인라인뿐만 아니라 크기 제로 구조체를 생략하다, 그래서이 될 것입니다 : 당신은이 같은 인수로 크기 제로 템플릿 구조체를 전달하여 그것을 할 수 있습니다 마치 회원 기능에 대해서만 전문화를 수행 한 것처럼 말입니다.

관련 문제