6

我想声明这样的事情:

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 };

但是当我尝试时,我得到了这个错误

错误:重新声明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我觉得这应该是合法的,因为任何给定的模板参数都不会定义多个。我能做些什么来帮助编译器理解这一点吗?

4

1 回答 1

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;
}

因为它没有超载,所以一个std::enable_if就足够了。enable if 被认为比没有专门化更专业化,一旦满足条件,它将被采用,保留非整数类型模板参数的默认情况。

活生生的例子

于 2019-06-14T12:54:53.953 回答