Any way to point a function pointer to a functor?

closed account (1yR4jE8b)
Consider the following snippet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class FunctionObject
{
	void operator()(int y, int j);
};


int main()
{
	void (*functorPointer)(int, int);
	FunctionObject* functor = new FunctionObject();
	functorPointer = functor;
	
	return 0;
}

void FunctionObject::operator()(int y, int j)
{
	using std::cout;
	
	cout << "Function Pointer To Functor";
}


This currently fails to compile with a:

$ g++ functor.cpp
functor.cpp: In function 'int main()':
functor.cpp:15: error: cannot convert 'FunctionObject*' to 'void (*)(int, int)' in assignment


Is there any way to point a function pointer at an object with an overloaded operator() so that when I dereference the function pointer it would call that operator? Or would I have to create a pointer to member of type operator().
Last edited on
No, they are fundamentally different. The functor receives a 'this' pointer as an implicit parameter.

But you can assign a Functor to a Functor* like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

class FunctionObject
{
public:
	void operator()(int y, int j);
};

int main()
{
	void (FunctionObject::*functorPointer)(int, int);
	functorPointer = &FunctionObject::operator();

	FunctionObject* functor = new FunctionObject();
	(functor->*functorPointer)(1, 3);

	return 0;
}

void FunctionObject::operator()(int y, int j)
{
	using std::cout;

	cout << "Functor Pointer To Functor";
}


But I can't think of many reasons to want to.
You can use boost::bind, which is just a more general way of doing what Galik did.

Warning: uncompiled:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <boost/bind.hpp>
#include <boost/function.hpp>

struct FunctionObject {
   void operator()( int x, int y ) const
       { std::cout << "operator()( " << x << ", " << y << ")" << std::endl; }
};

int main() {
    FunctionObject  obj;
    boost::function<void(int, int)> fn = boost::bind( obj, _1, _2 );
    fn( 1, 3 );
}
Topic archived. No new replies allowed.