Tab*_*r33 10 c++ templates overloading type-constraints implicit-conversion
使用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
Run Code Online (Sandbox Code Playgroud)
我想在上面调用"B".我可以用演员来实现这一点Base,但为什么这是必要的?
我希望为所有不是从Base(内置类型等)派生的类型调用模板函数,但我希望从派生类型调用非模板重载Base,而不需要客户端显式转换.我也尝试使重载成为模板的特化,但在这种情况下会发生相同的行为.得到我正在寻找的东西的惯用方法是什么?
Jam*_*lis 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)
{
}
Run Code Online (Sandbox Code Playgroud)