c++ - 如何强制编译器选择特定的函数特化

标签 c++ templates

例如,我有两个类:

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_ifstd::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 { … }

Live demo

您基本上是根据模板参数激活/停用重载。

您还可以通过添加别名使内容略微更具可读性:

template<class Type>
using is_fooable = std::is_base_of<Foo, Type>;

Live demo

关于c++ - 如何强制编译器选择特定的函数特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162794/

相关文章:

c++ - boost::bind 作为左值对象

C++:从容器中提取N个最高元素

c++ - 为什么这个函数指针的可变参数模板参数推导失败?

c++ - 带有非类型模板参数的 std::enable_if

c++ - 查找文件的最后一个簇

c++ - 在C++语言中,如何创建一个指向数组的指针的新对象?

python - 在 Django 模板中迭代 Expando 的动态属性

c++ - 构建本身就是 shared_ptr 类型的模板化容器

c++ - Windows:直接读取另一个进程的内存

php - 从管理页面找出用于页面的 Wordpress 模板