Alexander Bily
Alexander Bily

Reputation: 965

C++ function template overload on template parameter

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)?

Upvotes: 5

Views: 1882

Answers (1)

Barry
Barry

Reputation: 302663

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.

Upvotes: 4

Related Questions