2012-07-02 3 views
1

클래스로 C++ 부분 템플릿 전문화를 시도하고 있습니다. 문제는 구문보다 구문에 관한 것입니다. 내가 노력 위 달성을 위해C++ templates 클래스와의 부분 전문화

int main() 
{ 
    ... 
    Reduce<int, float> r(new int, new float); 
    Reduce<int> r2(new int); // partial template specialization? 
    ... 
} 

: 사실은 내가 다음과 같은 뭔가를하고 싶지 여전히

Reduce<int> r2(new int); // error: wrong number of template arguments (1, should be 2) 

내가 : 위의 코드와

template <typename T, typename U> 
class Reduce { 
    public: 
    Reduce(T *t, U *u) { } 
}; 

template <typename T> 
class Reduce<T,T> { 
    public: 
    Reduce(T *t) { } 
}; 

, 나는 문 다음 사용할 수 없습니다 해야 할 일 :

Reduce<int, int> r2(new int); 

누군가가 설명 할 수 있습니다 : (1) 가능한 경우 내 원하는 구문을 얻을 수있는 방법 (2) 가능하지 않은 경우, 이유는 무엇입니까? 템플릿 선언

template <typename T> 
class Reduce<T,T> { 
    public: 
    Reduce(T *t) { } 
}; 

당신이 감소하는 2 개 템플릿 인수를 제공 할 필요가 있음을 알 수에서 (즉, 기술적 인 문제)

답변

5

두 번째 템플릿 유형에 대한 기본 유형을 지정하여 사용을 변경

template <typename T, typename U = T> 
class Reduce { 
    public: 
    Reduce(T *t, U *u) { } 
}; 

예를 들어 http://ideone.com/5RcEG를 참조하십시오.

+0

@Griwes, 나는 당신을 다음 아니에요? 왜 두 번째 매개 변수에 기본값이 필요합니까? ' r (새 문자, 새 부동 문자); 또는' r (새 문자) 줄이기 '; 두 유형이 같으면 두 번째 매개 변수가 없습니다. – hmjd

+0

@ Griwes, 당신의 다운 보닛 이었나요? 그렇지 않다면 설명해 주실 수 있습니까? – hmjd

0

.

template <typename T, typename U = int> 
class Reduce { 
    public: 
    Reduce(T *t, U *u) { } 
}; 

또는 첫 번째 템플릿 유형으로 동일하게 기본값 : 그래서 너무

Reduce<int,int> r2(new int) 
4

는 ultimatly하려는 작업에 따라이 나 해결책이 될 수도 있고 그렇지 않을 수도 있지만, 적어도 그것은 컴파일 :

template <typename... T> 
class Reduce; 

template <typename T, typename U> 
class Reduce<T,U> { 
    public: 
    Reduce(T *t, U *u) { } 
}; 

template <typename T> 
class Reduce<T> { 
    public: 
    Reduce(T *t) { } 
}; 

int main() 
{ 
    Reduce<int, float> r(new int, new float); 
    Reduce<int> r2(new int); // partial template specialization? 
}