C++: Is it posible to asign a method to a function-pointer-member (atribute) in the same class?

54 Views Asked by At

That's what I'm trying to do: I have a class whit a member (attribute) which is a function pointer. In the creator I want to assign some methods of the same class to that pointer (depending of some condition) and use it after in other methods. For example:

class monton
 {
 private:
 protected:
  
  bool (*comparador)(int a, int b);

  inline bool mayor(int a, int b) {return a > b;}
  inline bool menor(int a, int b) {return a < b;}
  ...

 public:
  monton (bool maximo = true)
   {
   if(maximo) comparador = mayor;
   else       comparador = menor;
   }
  ...
 };

When I compile this code in CodeBlocks, I get this error:

error: cannot convert ‘monton::mayor’ from type ‘bool (monton::)(int, int)’ to type ‘bool (*)(int, int)’|
2

There are 2 best solutions below

4
On BEST ANSWER

This error tells you that you are trying to assign a pointer to non-static member function to a variable of regular function pointer type. correct pointer declaration would be:

bool (monton::*comparador)(int a, int b);
// or even better with type alias
using t_ComparadorPointer = bool (monton::*)(int a, int b);
t_ComparadorPointer comparador;
0
On

An alternative solution. You have to make the comparador static.

#include <functional>

class Monton                                                                                                                                                                                  
{
  static std::function<bool(int, int)> comparador;
  static inline bool mayor(int a, int b) { return a > b; };
  static inline bool menor(int a, int b) { return a < b; };

public:
  Monton(bool maximo)
  {
    comparador = mayor;
    if(!maximo) comparador = menor;
  };
};

std::function<bool(int, int)> Monton::comparador;

int main()
{
  Monton monton(1);
  return 0;
}