This code here works just fine. It couts
True!
False!
As it should
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
//typedef bool(callback) (int, int);
typedef boost::function<bool(int, int)> callback;
void print_result(callback handle, int first, int second)
{
if(handle == nullptr)
return;
if(handle(first, second))
std::cout << "True!\n";
else
std::cout << "False!\n";
}
class Callback
{
public:
Callback(bool type) : m_type(type)
{}
bool operator() (int foo, int bar)
{
return m_type ? foo > bar : foo < bar;
}
private:
bool m_type;
};
int main()
{
print_result(Callback(false), 2, 3);
print_result(Callback(true), 2, 3);
return 0;
}
But unfortunately I must make it work with the good old function pointer. I never use them in my practice, and I don't know much about them. It's obvious here that signature "bool operator() (int foo, int bar)" is not easily convertible to "bool(callback) (int, int)".
The error code I get from gcc:
prog.cc: In function 'int main()':
prog.cc:34:18: error: cannot convert 'Callback' to 'bool (*)(int, int)'
print_result(Callback(false), 2, 3);
^~~~~~~~~~~~~~~
prog.cc:8:28: note: initializing argument 1 of 'void print_result(bool (*)(int, int), int, int)'
void print_result(callback handle, int first, int second)
~~~~~~~~~^~~~~~
prog.cc:35:18: error: cannot convert 'Callback' to 'bool (*)(int, int)'
print_result(Callback(true), 2, 3);
^~~~~~~~~~~~~~
prog.cc:8:28: note: initializing argument 1 of 'void print_result(bool (*)(int, int), int, int)'
void print_result(callback handle, int first, int second)
Is there anyway to solve it? By the way, I wouldn't mind having a different solution. For example, the bool parameter can be passed by using "boost::bind", but binding doesn't work either. For the same reason.
Ideas, anyone? Thanks in advance!
NOTE: I cannot change the signature of a "print_result" function. Solutions like "use X instead of a function pointer" are off the table.