C++ function template overload on template parameter

本小妞迷上赌 提交于 2020-06-14 07:14:03

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/36958312/c-function-template-overload-on-template-parameter

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