2011-07-29 5 views
3
template <class T, bool flag> 
class A 
{ 
    //... 
    void f() 
    { 
     std::cout << "false" << std::endl; 
    } 
    //... 
}; 

template<class T> 
void A<T, true>::f<T, true>() 
{ 
    std::cout << "true" << std::endl; 
} 

위의 코드는 잘못되었지만 컴파일되지 않지만 내가 할 일에 대한 아이디어를 얻습니다. 어떻게해야합니까?템플릿 클래스의 멤버 함수에 대한 전문화를 작성할 수 있습니까?

+1

는 컴파일러가 부분 템플릿 특수화를 수 있습니까 다음과 같이

, 당신은 f를 오버로드 할 수 있습니까? – QuentinUK

답변

5

클래스 중 하나의 메소드 만 전문화 할 수는 없습니다. 대개 동일한 T에 템플릿 중첩 클래스를 사용하여이를 해결할 수 있습니다.

template <class T, bool flag> 
class A 
{ 
    //... 
    template <class Q, bool flag> 
    class F_Helper 
    { 
     void operator()() 
     { 
      std::cout << "false" << std::endl; 
     } 
    }; 

    template <class Q> 
    class F_Helper<Q, true> 
    { 
     void operator()() 
     { 
      std::cout << "true" << std::endl; 
     } 
    }; 

    F_Helper<T> f; 
    //... 
}; 

확실히 당신은 포함하는 클래스의 this 포인터에 액세스해야하는 경우 더 보일러가 필요하다 약간.

#include <iostream> 

template <class T, bool flag> 
class A 
{ 
public: 
    void f() 
    { 
     std::cout << "false" << std::endl; 
    } 
}; 

template<class T> 
class A<T,true> 
{ 
public: 
    void f() 
    { 
     std::cout << "true" << std::endl; 
    } 
}; 

void main() 
{ 
    A<int, false> a; 
    a.f(); 

    A<int, true> b; 
    b.f(); 
} 
+0

감사합니다. @ 마크 B : 그렇다면'템플릿 클래스 F_Helper' 대신'template 클래스 F_Helper'를 사용해야하는 이유는 무엇입니까? –

0

당신은 전체 템플릿 클래스를 전문으로 할 수 있습니다 클래스 템플릿의 유효

template<typename T> 
void A<T, true>::f() 
{ 
    std::cout << "true" << std::endl; 
} 

부분적으로 클래스 템플릿의 특정 인수 클래스 템플릿의 멤버를 전문으로되지 않도록 : 당신은 무엇을하려고하는 것은 유효하지 않습니다

template<> 
void A<int, true>::f() 
{ 
    std::cout << "true" << std::endl; 
} 

하지만 당신은 모든 템플릿 인수를 제공해야 는 "A의 부분 특수화 멤버 함수 'f'를 <T, true>에 대해 정의합니다. 그러한 부분적 특수화가 없으므로 컴파일러에서 오류가 발생합니다. 모든 인수를 제공 할 수없는 경우

template <class T, bool flag> 
class A 
{ 
    template<typename, bool> struct params { }; 

    void f() 
    { 
     f(params<T, flags>()); 
    } 

    template<typename U> 
    void f(params<U, true>) { 
     std::cout << "true" << std::endl; 
    } 

    template<typename U, bool flag1> 
    void f(params<U, flag1>) { 
     std::cout << "dunno" << std::endl; 
    } 
}; 
0

-

2

는 다른 답변이 말하는 것과는 달리, 당신은이 멤버 함수를 전문으로 할 수 : 당신은 전체 클래스를 전문으로 할 필요가 Ideone link

#include <iostream> 

template <class T, bool flag> 
class A 
{ 
    //... 
    void f() 
    { 
     std::cout << "false" << std::endl; 
    } 
    //... 
}; 

template<class T> 
class A<T, true> 
{ 
    //... 
    void f() 
    { 
     std::cout << "true" << std::endl; 
    } 
    //... 
}; 
+0

감사합니다. 정확히 같은 문제가 발생했습니다. 여기에 추가 사례가 있습니다. http://fabionotes.blogspot.jp/2012/05/template-function-in-template-class.html –

관련 문제