Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation failure when using a base class reference as a predicate

Tags:

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

Inside another unrelated method, I have :

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

My intention is to use this functor as a compare function like this:

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

However, I get the following error:

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

What is the proper way to use my pointer to functor in that situation?

like image 420
Seçkin Savaşçı Avatar asked Aug 19 '26 11:08

Seçkin Savaşçı


1 Answers

Function objects are passed by value in standard algorithms. This means that the derivedFunctor object will be passed by value as a baseFunctor. Since baseFunctor is an abstract class that code cannot compile. (If it was not an abstract class the code would compile, but probably misbehave because of the object slicing problem.)

In order 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 avoids copying the functor and keeps a reference instead; and because it is directly callable and simply forwards arguments to the object reference.

like image 155
R. Martinho Fernandes Avatar answered Aug 25 '26 09:08

R. Martinho Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!