解决功能模板部分专业化问题

时间:2014-04-02 04:03:37

标签: c++ templates c++11

我可以制作这样的作品吗?

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);
}

1 个答案:

答案 0 :(得分:2)

通常有三种部分功能专业化解决方案(尽管你似乎有完全专业化):

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>;

转发模板args作为魔术函数args然后实现重载:

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