例如,我有两个类:
class Foo {
public:
const bool operator==(const Foo&) const;
template<class _Ty>
const bool operator==(const _Ty&) const;
};
class Bar : public Foo { };
像这样的代码:
Foo& foo;
Bar& bar;
const bool equality = (foo == bar);
显然,编译器会选择模板函数来计算这个表达式,因为变量 bar
需要转换为 Foo&
才能调用专门的 operator==
。但是有什么方法可以强制编译器(不将 Bar&
转换为 Foo&
)在参数是从 Foo
派生的类(例如添加/删除一些修饰符或其他东西)?
最佳答案
Is there any way how I can force a compiler (without casting Bar& into Foo&) to choose the specialization firstly instead of the template function when the argument is an instance of a class derived from Foo?
是的,你可以,使用类型特征。具体可以用std::enable_if
和 std::is_base_of
如下:
template<typename Type>
typename std::enable_if<
std::is_base_of<Foo, Type>::value,
const bool
>::type
operator==(const Type&) const { … }
template<typename Type>
typename std::enable_if<
!std::is_base_of<Foo, Type>::value,
const bool
>::type
operator==(const Type&) const { … }
您基本上是根据模板参数激活/停用重载。
您还可以通过添加别名使内容略微更具可读性:
template<class Type>
using is_fooable = std::is_base_of<Foo, Type>;
关于c++ - 如何强制编译器选择特定的函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162794/