Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function template overload on template parameter

Tags:

Should it be possible to overload function template like this (only on template parameter using enable_if):

template <class T, class = std::enable_if_t<std::is_arithmetic<T>::value>>
void fn(T t)
{

}
template <class T, class = std::enable_if_t<!std::is_arithmetic<T>::value>>
void fn(T t)
{

}

if conditions in enable_if don't overlap? My MSVS compiler complains, that 'void fn(T)' : function template has already been defined. If not, what is the alternative (ideally not putting enable_if anywhere else than into template parameters)?

like image 760
Alexander Bily Avatar asked Apr 30 '16 17:04

Alexander Bily


1 Answers

Default arguments don't play a role in determining uniqueness of functions. So what the compiler sees is that you're defining two functions like:

template <class T, class>
void fn(T t) { }

template <class T, class>
void fn(T t) { }

That's redefining the same function, hence the error. What you can do instead is make the enable_if itself a template non-type parameter:

template <class T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
void fn(T t) { }


template <class T, std::enable_if_t<!std::is_arithmetic<T>::value, int> = 0>
void fn(T t) { }

And now we have different signatures, hence different functions. SFINAE will take care of removing one or the other from the overload set as expected.

like image 72
Barry Avatar answered Sep 28 '22 03:09

Barry