Boost logo

Boost :

Subject: [boost] Getting the types of arguments for a bind.
From: Michael Marcin (mike.marcin_at_[hidden])
Date: 2008-10-10 14:29:15


I want to take a boost::bind functor and get the type of its arguments.

I can't find any sort of introspection api documented. I tried using mpl
but what I came up with doesn't seem to work.

Is there a way to do this?

A distilled version of my failed attempt follows

#include <boost/bind.hpp>
#include <boost/mpl/find.hpp>
#include <boost/type_traits/function_traits.hpp>

template< typename Function, int N > struct arg_n;
template< typename Function >
struct arg_n< Function, 1 >
{
    typedef typename boost::function_traits< Function >::arg1_type type;
};

template< typename Callback, int ArgN > struct arg_type;

template< typename Return, typename Signature, typename Args, int ArgN >
struct arg_type< boost::_bi::bind_t<Return,Signature,Args>, ArgN >
{
    typedef typename boost::mpl::find< Args, boost::arg<ArgN> >::type iter;
    // +1 for 0 based find vs 1 based arguments
    typedef typename arg_n<Signature,iter::pos::value + 1>::type type;
};

void foo( int a ) {}

template< typename Callback >
void bar( Callback cb )
{
    // trivial usage
    typedef typename arg_type< Callback, 1 >::type ArgType;
    cb( ArgType() );
}

int main()
{
    bar( boost::bind(&foo,_1) );
}

Thanks,

-- 
Michael Marcin

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk