为什么编译器在重载的非模板函数上选择此模板函数?

时间:2011-12-21 18:06:48

标签: c++ templates overloading implicit-conversion type-constraints

使用VC ++ 2010,给出以下内容:

class Base { };
class Derived : public Base { };

template<class T> void foo(T& t);  // A
void foo(Base& base);              // B

Derived d;
foo(d);                            // calls A
foo(static_cast<Base&>(d));        // calls B

我想&#34; B&#34;被称为上述。我可以通过演员Base实现这一点,但为什么这是必要的呢?

我希望为不是从Base(内置类型等)派生的所有类型调用模板函数,但我希望为从{{1派生的类型调用非模板重载无需客户端显式转换。我也尝试使重载成为模板的特化,但在这种情况下会发生相同的行为。得到我正在寻找的东西的惯用方法是什么?

2 个答案:

答案 0 :(得分:12)

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

您可以通过使用SFINAE(替换失败不是错误)来解决特定情况(如此问题),以防止(A)使用派生自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)
{
}

答案 1 :(得分:2)

正在选择模板版本,因为当使用类型Derived的参数调用时,它是一个比重载版本更好的匹配。您可以使用SFINAE从重载决策中删除模板版本,以便在使用BaseDerived类型的参数进行调用时选择其他版本。

#include <type_traits>
#include <iostream>

class Base { };
class Derived : public Base { };

template<class T> 
typename std::enable_if<
  std::is_base_of<Base, T>::value == false
>::type
foo(T&)  
{ 
  std::cout << "template foo" << std::endl; 
}


void foo(Base&)
{ 
  std::cout << "non-template foo" << std::endl; 
}


int main()
{
  Derived d;
  Base b;

  foo( d );
  foo( b );
}
相关问题