C++11 将基类引用用作谓词时编译失败

C++11 将基类引用用作谓词时编译失败,c++11,C++11,在另一个不相关的方法中,我有: class baseFunctor{ virtual ~baseFunctor() {} virtual bool operator()(const A& lhs, const A& rhs) = 0; }; class derivedFunctor : public baseFunctor{ bool operator()(const A& lhs, const A& rhs) override { /*impleme

在另一个不相关的方法中,我有:

class baseFunctor{
  virtual ~baseFunctor() {}
  virtual bool operator()(const A& lhs, const A& rhs) = 0;
};
class derivedFunctor : public baseFunctor{
  bool operator()(const A& lhs, const A& rhs) override { /*implementation*/ }
};
但是,我得到以下错误:

C2893未能专门化函数模板“void” std::make_heap(_RanIt,_RanIt,_Pr)'


在这种情况下,使用指向函子的指针的正确方法是什么?

函数对象在标准算法中按值传递。这意味着
derivedFunctor
对象将作为
baseFunctor
按值传递。因为
baseFunctor
是代码无法编译的抽象类。(如果它不是一个抽象类,代码将编译,但可能由于对象切片问题而出现错误行为。)

为了实现这一点,您可以使用类似于
std::reference\u wrapper

std::make_heap(vectorA.begin(),vectorA.end(),*functor);

这是因为引用包装器对象避免复制函子,而是保留引用;因为它是直接可调用的,只需将参数转发给对象引用。

为什么您的函子要将左值引用传递给非常量?它应该是
bool操作符()(常量和lhs,常量和rhs)
。另外,为什么要使用
new
创建函子?如果您真的需要在堆上创建它,请使用
std::make_unique
…@在我的例子中,vectorA中的行元素顺序驱动行为。我希望其他人通过实现其functor来改变行为。我还能如何实现我的目标?如果你真的需要运行时多态性,那么,你可以在堆上分配函子,使用继承,但是在现代C++中,不允许使用“裸代码<新< /Cord>”和拥有原始指针。code>unique_ptr和
make_unique
是在这种情况下您应该使用的工具。无论如何,即使假设您需要运行时多态性(即使用哪种比较算法在运行时才知道,那么模板不是可行的选择)考虑是否基于继承的解决方案是真正必要的:<代码> STD::函数< /C>通常更简单更灵活(您可能想阅读它)。
std::make_heap(vectorA.begin(),vectorA.end(),*functor);
std::make_heap(vectorA.begin(),vectorA.end(),std::ref(*functor));