const整数模板参数的条件

Dmi*_*try 2 c++ c++11

我可以通过检查const integere参数来选择模板方法吗?

我需要这样的东西

template <size_t N <= 90>
void f1(){....}

template <size_t N > 90>
void f2(){....}
Run Code Online (Sandbox Code Playgroud)

我的解决方案是

template <size_t N>
void f()
{
    N <= 90 ? f1(N) : f2(N);
}
Run Code Online (Sandbox Code Playgroud)

但我认为这个approch不是很好因为f()将始终在运行时调用(可能不是编译器非常聪明).这样想的最佳方法是什么?

Ker*_* SB 8

您可以尝试这样的简单标签调度实现:

#include <type_traits>

void f(std::integral_constant<bool, true>) { /* ... */ }
void f(std::integral_constant<bool, false>) { /* ... */ }

template <std::size_t N>
void f()
{
    f(std::integral_constant<bool, N <= 90>{});
}
Run Code Online (Sandbox Code Playgroud)

您可以通过将bool类型替换为更大的integeral或枚举类型并添加更多条件来将此方案扩展到更多条件.


Ded*_*tor 6

使用SFINAE直接转换和std::enable_if:

template <std::size_t N>
typename std::enable_if<N<90, void>::type
f(){....}

template <std::size_t N>
typename std::enable_if<N>=90, void>::type
f(){....}
Run Code Online (Sandbox Code Playgroud)

尽管如此,直接的解决方案在这个例子中看起来最好.