3

I wanted to pass a function object to a class, and the class will use the function object to do some job inside the class.

But the problem is that, I don't what the function object will be passed in. So I figured that, define a void * pointer in the class, this pointer will be initialized with the function object which will be passed in.

Code goes below:

class A 
{
    public:
        //...
        void doSomeJob(int x)
        {
            (*functor)(x); //use the function object to process data x
        }

    private:
        //...
        void *functor; //function object's pointer will be assigned to this pointer
};

But the code doesn't work. I guess, can't use void *functor that way.

I know I can use template class to finish the job, but my question is, can I still do the job using pointer to function object and how?

PS

To make my problem clearer, there may be several function objects which differ from each other by how they process data, I don't what function object will be passed in, but I do know each of them will take a int parameter.

Just as some answers tell, I can do the job through function pointer, but function object has more utilities than function pointers, such as states, and that's what I'm gonna use.

Alcott
  • 17,905
  • 32
  • 116
  • 173

4 Answers4

9

You can't call a function object of a type unknown to you at the call site if its type is not stored somewhere accessible to the call machinery.

There are two options:

If you can use C++11 or boost, you can use std::function resp. boost::function:

class A
{
public:
  // ...
  void doSomeJob(int x)
  {
    functor(x);
  }
private:
  std::function<void(int)> functor; // or boost::function when using boost
};

Here the type is stored (in an implicit form) inside the mechanism of the function template.

Otherwise, if you can require that all function objects passed have a class type derived from a specific base class, you can create an abstract base class:

struct AbstractFunctor
{
  virtual void operator()(int) = 0;
};

class A
{
public:
  // ...
  void doSomeJob(int x)
  {
    (*functor)(x);
  }
private:
  AbstractFunctor* functor; // or boost::function when using boost
};

Here the type is stored in the virtual table of the function object.

If you really can't use boost, you also might write a similar solution yourself. The key word is "type erasure", and it basically works by generating on the fly a derived object from a known base class (as in my second solution) which knows about your object's type and can call it. It might be done roughly as follows (untested code):

class int_function
{
private:
  struct abstract_forward
  {
    virtual void call(int) = 0;
    virtual abstract_forward clone() const = 0;
    virtual ~abstract_forward() {}
  };
  template<typename Functor> struct forward: abstract_forward
  {
    forward(Functor f): func(f) {}
    void call(int i) { func(i); }
    abstract_forward clone() const { return new forward<Functor>(func); }
    Functor func;
  };
public:
  template<typename Functor> int_function(Functor f)
  {
    forwarder = new forward<Functor>(f);
  }
  int_function(int_function const& other)
  {
    forwarder = other.forwarder->clone();
  }
  int_function& operator=(int_function const& other)
  {
    abstract_forward* newfwd = other.forwarder->clone();
    delete forwarder;
    forwarder = newfwd;
  }
  ~int_function()
  {
    delete forwarder}
  }
  void operator()(int i)
  {
    forwarder->call(i);
  }
private:
  abstract_forward* forwarder;
};

class A
{
public:
  void doSomeJob(int x)
  {
    functor(x);
  }
private:
  int_function functor;
};
celtschk
  • 19,311
  • 3
  • 39
  • 64
  • I don't use C++11 or boost. So, I cannot do it through a simple pointer like in my code, right? – Alcott Jan 15 '12 at 12:30
  • @Alcott: My second solution doesn't use anything which wasn't part of C++ since before it first got standardized. However it places some restruction on your function objects (class must be derived from `AbstractFunctor`). BTW, any reason why you can't use boost? – celtschk Jan 15 '12 at 12:53
  • @Alcott: I've now added how to write something in the spirit of `boost::function` yourself, without using boost or other libraries. – celtschk Jan 15 '12 at 13:13
  • Well, I don't use boost because I'm not familiar with this lib, is it popular or already standardized? – Alcott Jan 15 '12 at 13:21
  • Thank you very much for your detailed answer. BTW, is something wrong with the destructor of the in-class `struct abstract_forward`? – Alcott Jan 15 '12 at 13:26
  • @Alcott: Well, quite some parts of boost (*in particular* boost::function) have basically found their way into C++11. In general boost libraries are of high quality and very portable, and moreover they have a permissive license. Also boost is really a set of libraries, so you don't have to learn complex specialized libraries like boost::graph or boost::spirit just to use simple and generally useful libraries like boost::function, boost::optional or the smart pointers. – celtschk Jan 15 '12 at 13:30
  • @Alcott: Yes, thanks, the destructor was wrong. I've fixed it. As I wrote: It's untested code. – celtschk Jan 15 '12 at 13:31
2
void *functor; //function object's pointer will be assigned to this pointer

This is not function pointer.

What you need is this:

void (*functor)(int); //function pointer

Even better is this (in C++11):

#include <functional> //must include this 

std::function<void(int)> functor;

//then use it as:
functor(x);  //not (*functor)(x)
Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

The correct syntax is:

void (*functor)(int);

Also see this tutorial for more about declaring and using function pointers: http://www.cprogramming.com/tutorial/function-pointers.html

Tudor
  • 61,523
  • 12
  • 102
  • 142
1

C++ is very strict about its types, so you can't just use a void* as function pointer. The pointer must be an actual function pointer for you to call it.

What do you mean you don't know what function object will be passed in? In that example, you know that it takes an int or int& as a parameter and probably returns void, for example, so you can store the function pointer as:

void (*func)(int);

If you mean to say that you want to be able to store class member functions as well, or instances of classes that overload operator(), then you can use std::function and std::bind from <functional> if you have C++11, or boost::function and boost::bind:

boost::function<void (int)> func;
Paul Manta
  • 30,618
  • 31
  • 128
  • 208
  • Yes, I mean `function object`, not `function pointer`. I don't which function object will be passed in, but I do know any function object passed in will take an `int` parameter, so I want to initialize `void *functor` with the pointer to the instance of the function object. – Alcott Jan 15 '12 at 09:50
  • @Alcott Then using `std::function` (`boost::function`) is definitely the way to go. It can handle any kind of callable object (not just functions) as long as the return types and parameters match. Read the documentation from the links I provided, they're definitely very useful libraries to know about. – Paul Manta Jan 15 '12 at 09:52