且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么编译器选择此模板函数而不是重载的非模板函数?

更新时间:2023-11-02 15:54:40

在所有条件都相同的情况下,非模板函数优于函数模板.但是,在您的情况下,所有条件都不相等:(A)与T = Derived完全匹配,但是(B)需要参数的派生到基数转换.

All things being equal, nontemplate functions are preferred over function templates. However, in your scenario, all things are not equal: (A) is an exact match with T = Derived, but (B) requires a derived-to-base conversion of the argument.

您可以通过使用SFINAE(替代失败不是错误)来解决特定情况(如这种情况)的情况,以防止使用从Base派生的类型实例化(A):

You can work around this for specific cases (like this one) by using SFINAE (substitution failure is not an error) to prevent (A) from being instantiated with a type that is derived from Base:

#include <type_traits>
#include <utility>

template <typename T>
typename std::enable_if<
    !std::is_base_of<Base, T>::value
>::type foo(T& x)
{
}

void foo(Base& x)
{
}