Search code examples
c++function-pointers

pass multiple class function pointer as function parameter in c++


I am newly learning function pointer and able to pass function pointer between classes. Now i am looking to receive function pointer parameter of all the other classes.

fncptr2.h

 #ifndef FNCPTR2
 #define FNCPTR2

 class fncptr1;

 class fncptr2
 {
    public:
      int implfncptr(int (fncptr1::*add)(int,int));
 }; 

 #endif 

fncptr2.cpp

#include "fncptr2.h"
#include "fncptr1.h"
#include <iostream>

using namespace std;

fncptr1 ff;

int fncptr2::implfncptr(int (fncptr1::*add)(int, int))
{
   return (ff.*add)(1,2);
}

fncptr1.h

#ifndef FNCPTR1
#define FNCPTR1

class fncptr1
{
  public:
    int addition(int a,int b);
    void testfncptr();

};

#endif 

fncptr1.cpp

   #include "fncptr1.h"
#include "fncptr2.h"
#include <iostream>

using namespace std;

int fncptr1::addition(int a,int b)
{
    return a + b;
}

void fncptr1::testfncptr()
{
   fncptr2 f;
   f.implfncptr(&fncptr1::addition);
 }

main.cpp

fncptr1 f;
f.testfncptr();

The above sample code works fine. Now looking to receive all the function pointers in

int implfncptr(int (fncptr1::*add)(int,int));

Instead of receive fncptr1 function pointer , looking to receive the function pointers from all the other classes

Example

int implfncptr(int (AllClassInstance::*add)(int,int));

Solution

  • Okay, your question doesn't quite make sense, but it sounds like what you want is a more generic solution. First, I don't use function pointers the way you've got them. This is very C-style, and there are better ways. My definition of "better" means "fits more solutions". There might be a very slight performance hit for the way I prefer.

     #include <functional>
    
     class Foo {
     public:
         typedef std::function<bool(std::string &)> MyFunct;
    
         void someMethod(MyFunct funct) {
             std::string str = "Foo";
             if (funct(str)) {
                 ...
             }
         }
     };
    
     // Then somewhere else, you can do this:
    
    
     bool f(const std::string &str) {
         return str.length() > 10;
     }
    
     Foo foo;
     foo.someMethod(f);
    

    But the reason I like this is that you can also use lambdas:

     Foo foo;
     foo.someMethod([](const std::string &str) { return str.length() > 10; });
    

    Or you can pre-define the lambda like this:

     Foo::MyFunct f = [](const std::string &str) { return str.length() > 10; };
    
     foo.someMethod(f);
    

    I don't know if this actually helps you advance what you're trying to do, as your question isn't quite clear as I write this answer. But this might help by providing a few other ways to accomplish what you want.

    I'm sure there's an argument for C-style function pointers, but the functional interface offers better features, in my view.