Reputation: 1123
How does boost::function take a function pointer and get parameters from it? I want wrap a function pointer so that it can be validated before being called. And it would be nice to be able to call it like boost::function is with the () operator and not having to access the function pointer member.
Wrapper func; func(5); //Yes :D func.Ptr(5) //Easy to do, but not as nice looking
Upvotes: 2
Views: 398
Reputation: 84159
Something like this?
class Functor
{
public:
/// type of pointer to function taking string and int and returning int
typedef int ( *func_ptr_t )( const std::string&, int );
explicit Functor( func_ptr_t f ) : fptr_( f ) {}
int operator()( const std::string& s, int i ) const { return fptr_( s, i ); }
private:
func_ptr_t fptr_; //< function pointer
};
But why not just use boost::function
? It allows for way more then just a function pointer.
Upvotes: 0
Reputation: 355039
You need to overload operator()
. To determine the return type, arity, and parameter types of a function, you can use something like Boost.TypeTraits:
#include <boost/type_traits.hpp>
template <typename Function>
struct Wrapper
{
typedef typename boost::function_traits<Function>::arg1_type Arg1T;
typedef typename boost::function_traits<Function>::result_type ReturnT;
Wrapper(Function func) : func_(func) { }
ReturnT operator()(Arg1T arg) { return func_(arg); }
Function* func_;
};
bool Test(int x) { return x < 42; }
int main()
{
Wrapper<bool(int)> CallsTest(&Test);
CallsTest(42);
}
Upvotes: 2