我可以做这样的事情吗?
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);
}
最佳答案
通常是部分函数特化的三个解决方案(尽管您似乎拥有完全特化):
std::enable_if / std::disable_if
例如:
template<int X, int Y>
typename std::enable_if<X == 0 && Y == 0>::type
int f();
将实现委托(delegate)给一个结构(对我来说似乎是最干净的):
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
关于c++ - 解决功能模板部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22801330/