Why is the compiler choosing this template function over an overloaded non-template function?

后端 未结 2 773
一生所求
一生所求 2021-01-11 20:45

Using VC++ 2010, given the following:

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

template void foo(T& t);  // A
void foo(Base&          


        
2条回答
  •  耶瑟儿~
    2021-01-11 21:25

    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.

    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 
    #include 
    
    template 
    typename std::enable_if<
        !std::is_base_of::value
    >::type foo(T& x)
    {
    }
    
    void foo(Base& x)
    {
    }
    

提交回复
热议问题