c++ - 解决功能模板部分特化

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

最佳答案

通常是部分函数特化的三个解决方案(尽管您似乎拥有完全特化):

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/

相关文章:

c++ - 如何使用(可变)模板进一步概括这一点

c++ - 无法在 C++ 模板的初始化列表中使用 lambda

c# - 如何处理托管 C++ (/CLR) 中 #using 语句中的错误

c++ - 分析 WinDbg 中的崩溃

c++ - 如何在 C++ 中创建事务流?

c++ - 如何在 pkg-config 中使用 C++ Boost 库?

c++ - 对不同类型使用具有不同返回值的模板函数不起作用

c++ - 如何定义和设置指向模板类方法的函数指针

c++ - const ref 类型的函数参数模板参数不明确

c++ - 从 C++ 中的字符串解析键/值对