模板参数上的 C++ 函数模板重载

标签 c++ templates overloading

是否可以像这样重载函数模板(仅在使用 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)' : function template has already been defined。如果不是,替代方案是什么(最好不要将 enable_if 放在模板参数以外的任何地方)?

最佳答案

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

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

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

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

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 将负责按预期从重载集中移除一个或另一个。

关于模板参数上的 C++ 函数模板重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36958312/

相关文章:

c++ - 如何使用通用函数/插槽连接到 boost::signal?

c++ - boost 信号和传递类方法

c++ - 没有模板的 ADL

c++ - 函数重载中的 int 和 float

c++ - 枚举类的关系运算符重载

c++ - 具有共享私有(private)数据的模板函数

c++ - Linux 文件读写 - C++

java - 在 UML 中表示重载方法

c++ - 逻辑 : B contained by set A 的模板和 C++ 运算符

c++ - 如何公开模板模板参数