0

I have the following code:

#include <iostream>
using namespace std;

class A
{
    int m_value;
public:
    A(int value)
    {
        m_value = value;
        funcA(&A::param);
    }

    void funcA(void (A::*function)(int))
    {
        (this->*function)(m_value);
    }

    void param(int i)
    {
        cout << "i = " << i << endl;
    }
};


int main()
{
    A ob(10);

    return 0;
}

I have a class in which I call a function that receives another function as parameter. The function call is at line funcA(&A::param). What I want is to be able to pass a function as parameter without being necessary to specify the class scope: funcA(&param). Also I didn't want to use typedefs that's why I have the code a little 'dirty'.

Is there any possibility to achieve this?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Jacob Krieg
  • 2,834
  • 15
  • 68
  • 140
  • It is just an experimental example. The useful thing in this is a little complex and it's too much to explain. It can be applied if this class is made to be inherited so the user can pass functions as parameters easier. – Jacob Krieg Aug 31 '12 at 15:17
  • Well however complex the application of what you're intending to achieve, it's most likely less confusing than what you've shown here. Just show us what you're actually trying to achieve. – Aesthete Aug 31 '12 at 15:22

3 Answers3

0

That is kind of ugly.

The first thing you should look at doing is recoding things to use inheritence and dynamic dispatch instead. To do this you change the A class to have a virtual method that funcA calls

class A {
...
    void funcA () {
       custom_function(m_value);
    }
protected:
   virtual void custom_function (int)=0;
}

Now for every different custom_function you want to use, you declare a new class derived from A, and implement the function in there. It will automagically get called from funcA:

class A_print : public A {
public:
    virtual void custom_function (int param) { 
       std::cout << "param was " << param << std::endl;
    }
}

If that isn't flexible enough for you, the next best C++-ish solution would be to implement a functor (an object that acts as a function, possibly even overriding the ()operator.

Community
  • 1
  • 1
T.E.D.
  • 44,016
  • 10
  • 73
  • 134
0

This cannot be done. A function pointer in a class must be identified using the class scope (A::function)

Jacob Krieg
  • 2,834
  • 15
  • 68
  • 140
-1

I don't understand why you can't just do this:

#include <iostream>
using namespace std;

class A
{
    int m_value;
public:
    A(int value)
    {
      param(value);
    }

    void param(int i)
    {
        cout << "i = " << i << endl;
    }
};

int main()
{
    A ob(10);
    return 0;
}
Aesthete
  • 18,622
  • 6
  • 36
  • 45