问题描述
我想声明如下:
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 };
但是当我尝试我收到此错误时:
错误:重新声明templateconstexpr std::enable_if_t::value, int []>foo
注意:之前的声明 templateconstexpr std::enable_if_t::value, int []>foo
我觉得这应该是合法的,因为为任何给定的模板参数定义的 foo
永远不会超过一个.我可以做些什么来帮助编译器理解这一点?
I feel like this should be legal as there will never be more than one foo
defined for any given template argument. Is there something I can do to help the compiler understand this?
推荐答案
不用重载.
您使用 enable if 的声明很好,但不能有多个,因为变量不可重载.
Your declaration with the enable if is fine, but you cannot have mutiple of them, since variables are not overloadable.
专业化,就像类一样,它工作得很好:
With specialisation, just like with classes, it works just fine:
#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 被认为比没有特殊化更专业,一旦满足条件就会被采用,为非整型模板参数保留默认情况.
Since it's not overloading, a single std::enable_if
is enough. The enable if is considered more specialized than no specialization, it will be taken as soon as the condition is met, leaving the default case for non integral type template parameter.
这篇关于我可以重载模板变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!