0
#include<functional>
#include<list>

class A {
  public: virtual bool isOdd(int x) = 0;
};

class B : public A {
  public: bool isOdd(int x) override 
    { return (x%2)!=0; }
};

int main () {
  A *a = new B();
  std::list<int> l {1,2,3,4};
  l.remove_if(a->isOdd);
  return 0;
}

This code produces the following compiler error for l.remove_if(a->isOdd);:

reference to non-static member function must be called

How can I call remove_if so that the isOdd implementation of class B is called?

I'm not looking for a solution that directly references B::isOdd. Instead, I want to have a pointer to the abstract class A and multiple (non-abstract) subclasses of A and use the implementation of whatever derived class the pointer points to.

Jörg Kirchhof
  • 1,530
  • 1
  • 9
  • 19
  • 3
    `l.remove_if([a](int n) {return a->isOdd(n); });`. – Jarod42 May 15 '18 at 19:59
  • you are mixing two orthogonal problems here. The error complains because `remove_if` expects a function that it can call (which `a->isOdd` isnt, and unfortunately the error is a bit misleading) and the second thing is `isOdd` being virtual, but it isnt clear why you need it to be virtual or why you think this would be a problem – 463035818_is_not_an_ai May 15 '18 at 20:01
  • 1
    `std::function f = std::bind( &A::isOdd, a, _1 ); l.remove_if(f)` – Stephan Lechner May 15 '18 at 20:04
  • Thank you, @Jarod42, I did not think of using lambdas here. – Jörg Kirchhof May 15 '18 at 20:05
  • @StephanLechner: Better to use `auto` instead of type erase type with unneeded `std::function`. – Jarod42 May 15 '18 at 20:09

0 Answers0