I want to implement the ability to pass a pointer to a method of different classes as a function argument.

class A1 { public: void show() { std::cout << "A1" << std::endl; } }; class B1 { public: void show() { std::cout << "B1" << std::endl; } }; void callf(void (*fp)()) { fp(); } int main() { callf(&A1::show); callf(&B1::show); return 0; } 
  • 2
    "Pointer to non-static class method" is not a "function pointer". These two categories of types are fundamentally different and not compatible with each other. In your program there is some attempt to call a class method without creating a single class object. This is obviously a complete nonsense. Explain in more detail what exactly you want to do. - AnT
  • one
    @AnT they are different, but not too much - both are representable as std :: function. And in some languages ​​this is literally the same type — fundamentally for a programmer, this is a manifestation of the concept of the object being called. The intention callf() is a special case of std::invoke() . - jfs

1 answer 1

In your version, a trifle is forgotten - the fact that a non-static member function requires an object for which it is called. So you just can't call it, you need an object.

Or static function.

Here it is - easily:

 class A1 { public: static void show() { std::cout << "A1" << std::endl; } }; class B1 { public: static void show() { std::cout << "B1" << std::endl; } }; void callf(void (*fp)()) { fp(); } int main() { callf(&A1::show); callf(&B1::show); return 0; } 

If, however, not static - for example, here:

 class A1 { public: void show() { std::cout << "A1" << std::endl; } }; class B1 { public: void show() { std::cout << "B1" << std::endl; } }; template<class T> void callf(T& t, void (T::*f)()) { (t.*f)(); } int main() { A1 a; B1 b; callf(a,&A1::show); callf(b,&B1::show); return 0; }