2014-04-02 2 views
0

이 작업을 수행 할 수 있습니까?함수 템플릿 부분 특수화

template <int N, int Y> 
constexpr int f(char *(&arr)[Y]) 
{ 
    return N * f<N - 1, Y - 1>(); 
} 

// Y must appear here too because it's used in parameters 
// and if I remove this I get "no matching function" error 
template <int N, int Y> 
constexpr int f<1, 1>(char *(&arr)[Y]) // run this when Y == 0 and N == 0 
{     
    return 1; 
} 

int main() 
{ 
    size_t x = f<4,4>(); 
    printf("x = %zu\n", x); 
} 
+0

'Y'는 중복되지 않습니까? – legends2k

+0

@ legends2k : 코드 예입니다. 함수 자체가별로 의미가 없을 수도 있습니다. –

+0

크기가 0 인 배열을 가질 수 없으므로,'arr' 매개 변수가 필요하다면 다른 것을 전문화해야합니다 - 아마도'1'의'Y'입니다. 또한 전문화는'template <>'이어야합니다 ('int N, int Y'를 ​​제거하십시오). 그리고 호출의 재귀 적 특성을 고려할 때 흥미로운 배열을 제공해야합니다. 아마도 더 짧은 배열에 대한 참조로 캐스트를해야 할 것입니다. –

답변

2

일반적으로 부분적인 기능의 전문화를위한 세 가지 솔루션 (당신이 전체 전문성을 갖고있는 것 같다 altho) :

std::enable_if/std::disable_if 

예 : 구조체에

template<int X, int Y> 
typename std::enable_if<X == 0 && Y == 0>::type 
int f(); 

위임 구현 (나에게 깨끗한 것) :

template<int X, int Y> 
struct f_impl { 
    int eval(); 
}; 

template<int X, int Y> 
int f() { 
    return f_impl<x,Y>::eval(); 
} 

하고 부분적으로 구현을 마법 함수의 인수로서

template<> 
struct f_impl<0,0>; 

전달 템플릿 인수을 공급하고 구현 과부하 :

template<int X, int Y> 
int f(mpl::int_<X>, mpl::int_<Y>); 

int f(mpl::int_<0>, mpl::int_<0>); 

template<int X, int Y> 
int f() { 
    f(mpl::int_<X>(), mpl::int_<Y>()); 
} 

는 포장 유형에 대해 더 메타 프로그래밍 헬퍼 boost::mpl에 예 mpl::identity 맡기 http://www.boost.org/doc/libs/1_55_0b1/libs/mpl/doc/index.html