Can I overload template variables?

旧街凉风 提交于 2019-12-06 01:39:02

问题


I want to declare something like this:

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

But when I try to I'm getting this error:

error: redeclaration of template<class T> constexpr std::enable_if_t<std::is_floating_point<_Tp>::value, int []> foo
note: previous declaration template<class T> constexpr std::enable_if_t<std::is_integral<_Tp>::value, int []> foo<T>

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?


回答1:


Not with overloading.

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

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.

Live example



来源:https://stackoverflow.com/questions/56598489/can-i-overload-template-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!