我可以重载模板变量吗?

Jon*_*Mee 6 c++ templates overloading enable-if template-variables

我想声明如下内容:

template <typename T>
constexpr enable_if_t<is_integral_v<T>, int[]> foo = { 1, 2 };

template <typename T>
constexpr enable_if_t<is_floating_point_v<T>, int[]> foo = { 10, 20, 30 };
Run Code Online (Sandbox Code Playgroud)

但是当我尝试出现此错误时

错误:template<class T> constexpr std::enable_if_t<std::is_floating_point<_Tp>::value, int []> foo
注释的重新声明:先前的声明template<class T> constexpr std::enable_if_t<std::is_integral<_Tp>::value, int []> foo<T>

我觉得这应该是合法的,因为foo对于任何给定的模板参数,永远不会定义多个。有什么我可以帮助编译器理解的吗?

Gui*_*cot 8

没有过载。

使用enable if的声明很好,但是由于变量不可重载,因此不能使用多个声明。

通过专业化,就像使用类一样,它也可以正常工作:

#include <iostream>
#include <type_traits>

using namespace std;

template <typename T, typename = void>
constexpr int foo[] = {10, 20, 30};

template <typename T>
constexpr int foo<T, enable_if_t<is_integral_v<T>>>[] = { 1, 2 };


int main() {
    cout << foo<int>[0] << endl;
    cout << foo<float>[0] << endl;
}
Run Code Online (Sandbox Code Playgroud)

由于没有过载,所以一个std::enable_if就足够了。如果认为enable if比没有专门化更专门,则会在满足条件后立即采用,如果非整数类型模板参数保留默认情况。

现场例子