Compilation error when using base class reference as predicate

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*/ }
};

      

Inside another unbound method, I have:

baseFunctor* functor = new derivedFunctor();
std::vector<A> vectorA;

      

I intend to use this functor as a comparison function, for example:

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

      

However, I am getting the following error:

C2893 Failed to define function template void std :: make_heap (_RanIt, _RanIt, _Pr)

What is the correct way to use my functor pointer in this situation?

+3


source to share


1 answer


Function objects are passed by value in standard algorithms. This means that the object derivedFunctor

will be passed by value as baseFunctor

. Because it baseFunctor

is an abstract class whose code cannot be compiled. (If it weren't for an abstract class, the code would have compiled, but probably got it wrong due to an object clipping issue.)

To make this work, you can use something like std::reference_wrapper

:



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

      

This works because the reference wrapper object does not allow the functor to be copied and instead stores the reference; and because it's directly callable and just forwards the arguments to an object reference.

+7


source