tags:

views:

74

answers:

2

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
+1  A: 

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);
}
James McNellis
I understand that, but how do you go from a function pointer to parameters so you can overload it?
Thanks for the code, I think that is what I am looking for.
A: 

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.

Nikolai N Fetissov
I guess I could. I would need a way of inheriting from it and overloading the () operator though. I don't want to inline the parameters like you did in your example.
Hmm, I don't see a point here. Why do you need a wrapper around a function pointer and inherit from it? `boost::function`, on the other hand, will allow you to point to any signature-confirming callable object, *and* allow to store it by value, which is very handy with STL containers.
Nikolai N Fetissov
I will check out the callable object then. Because I need to before calling the function verify that it is valid. I am trying to make it easy to call member functions from a dynamically loaded dll. So before calling it, if its null it will try to get it with GetProcAddress and if it is still null it will return.
I think this is too much trouble/too generic for lazy library loading. Also, I'd raise an exception if library doesn't load or required function is not found instead of just returning (what?) - at least the upper layers know there's a problem.
Nikolai N Fetissov