I try to write a functor to call a boost function with bind and some template. So i have this main :
int function(char c)
{
std::cout << c << std::endl;
return (0);
}
int main()
{
Function<int (char)> fb = boost::bind(&function, _1);
fb('c');
return (0);
}
and this is my class Function
:
template<typename F>
class Function
{
private:
F functor;
public:
Function()
{
this->functor = NULL;
};
Function(F func)
{
this->functor = func;
};
template <typename P>
void operator()(P arg)
{
(*this->functor)(arg);
};
void operator=(F func)
{
this->functor = func;
};
};
i have a problem : when i try to compile i have these errors :
error C2440: 'initializing' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'Function<F>'
IntelliSense: no suitable user-defined conversion from "boost::_bi::bind_t<int, int (*)(char), boost::_bi::list1<boost::arg<1>>>" to "Function<int (char)>" exists
Someone can help me ?
boost::bind
will return something unspecified, but convertible to a
boost::function
. There is no reason for you to have your own
function
class.
Look at this simple example:
#include <boost/bind.hpp>
#include <boost/function.hpp>
int func(char) { return 23; }
int main()
{
boost::function<int(char)> bound = boost::bind(func, _1);
return 0;
}
What does that unspecified
return type mean for your case? You need to erase the type of Function
and
need to write something called AnyFunction
. Why? Because you will never be able to spell out the type of the template argument of Function
in C++03 (and even C++11, for e.g. accepting only a specific type as a function argument).