模板参数上的 C++ 函数模板重载 [英] C++ function template overload on template parameter

查看:58
本文介绍了模板参数上的 C++ 函数模板重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像这样重载函数模板(仅在模板参数上使用 enable_if):

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

}

如果enable_if 中的条件不重叠?我的 MSVS 编译器抱怨 'void fn(T)' :函数模板已经定义.如果不是,那么替代方法是什么(理想情况下不要将 enable_if 放在模板参数之外的任何地方)?

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

推荐答案

默认参数在确定函数的唯一性方面不起作用.所以编译器看到的是你定义了两个函数,如:

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) { }

那是重新定义了相同的函数,因此出现了错误.您可以做的是使 enable_if 本身成为模板非类型参数:

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) { }

现在我们有不同的签名,因此有不同的功能.SFINAE 将按照预期从过载集中删除一个或另一个.

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.

这篇关于模板参数上的 C++ 函数模板重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆