解决函数模板部分专用化问题

work around function template partial specialization

本文关键字:问题 专用 函数模板部 解决      更新时间:2023-10-16

我可以做这样的事情吗?

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 = %zun", x);
}
通常有

三种用于部分函数专业化的解决方案(尽管您似乎具有完全专业化):

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