2012-11-02 3 views
1

나는이 같은이 "과부하"원하는 템플릿 구조를 가지고 :C++ 선언의 외부 템플릿 멤버 함수 정의는

($ g++ test.cpp -o test) 
test.cpp:11:6: error: 'template<class T, class U> struct foo' used without template parameters 
test.cpp:11:30: error: 'void operator()(T, U)' must be a nonstatic member function 
:

#include <iostream> 

template <typename T, typename U = int> 
struct foo { 
    void operator()(T, U); 
} 

template <typename T, typename U = int> 
void foo::operator()(T a, U b){ 
    std::cout << "T, U()\n"; 
} 

template <typename T> 
struct foo<T, int> { 
    void operator()(T); 
} 

template <typename T> 
void foo<T, int>::operator()(T a){ 
    std::cout << "T()\n"; 
} 

int main(int argc, char **argv){ 
    foo<int> a; 
    foo<int, char> b; 

    a(1); 
    b(2, 'b'); 

    return false; 
} 

을하지만 다음과 같은 오류가 컴파일에

foo < T, int> :: operator()의 정의가 완벽하게 작동하기 때문에 이상합니다. 또한 다음과 같이 함수를 인라인으로 정의하면 :

template <typename T, typename U = int> 
struct foo { 
    void operator()(T a, U b){ std::cout << "T, U()\n"; } 
} 

문제없이 작동합니다.

답변

2

당신은, foo<T,U>::operator() 푸 지정할 그 템플릿 매개 변수를 사용해야합니다. 정의에서 기본 템플리트 매개 변수 값을 제거하십시오.

template <typename T, typename U> // don't use a default parameter 
void foo<T,U>::operator()(T a, U b){ // don't forget the <T,U> here 
    std::cout << "T, U()\n"; 
} 

또한 템플릿 클래스 정의 뒤에 세미콜론을 깜박입니다.

0

함수 프로토 타입에 기본 템플릿 매개 변수를 한 번만 지정할 수 있습니다 (함수에 프로토 타입이있는 경우).

template <typename T, typename U = int> void f(); 
// .... 

template <typename T, typename U = int> void f() {} 

이는 불필요합니다. 단순히합니다

template <typename T, typename U> void f() {} 
관련 문제