Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I overload template variables?

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?

like image 576
Jonathan Mee Avatar asked Jun 14 '19 12:06

Jonathan Mee


1 Answers

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

like image 97
Guillaume Racicot Avatar answered Oct 20 '22 12:10

Guillaume Racicot