Is there a way to deduce the signature of a lambda as an mpl sequence?
Asked Answered
P

1

6

Is there a way to deduce the signature, result- and parameter-types, of a c++0x lambda as a Boost.MPL sequence, for example a boost::mpl::vector? For example, for a lambda

[]( float a, int b ) -> void { std::cout << a << b << std::endl; }

I would like to get a boost::mpl::vector<void,float,int>.

Plutonian answered 19/12, 2010 at 11:8 Comment(0)
P
6

C++0x lambdas which are "closure-objects" are functors. So you can use boost.Boost.FunctionTypes to decompose its operator().

Example:

#include <boost/function_types/parameter_types.hpp>

#include <boost/mpl/at.hpp>
#include <boost/mpl/int.hpp>

int main()
{
    int x = 1;
    auto f = [x](char a, short b, int c){ return x; };

    typedef decltype(f) lambda_t;
    typedef boost::function_types::parameter_types<
        decltype(&lambda_t::operator())>::type args_t;
    // we can use boost::mpl::identity<decltype(f)>::type instead of lambda_t

    static_assert(sizeof(boost::mpl::at<args_t, boost::mpl::int_<1>>::type) == 1, "");
}
Pedaias answered 19/12, 2010 at 11:18 Comment(2)
How exactly would I do that? I tried parameter_types, result_type and components, both on the functor itself and on its operator(), but I couldn't get it to work.Plutonian
Thanx for the sample. I ended up pop'ing from parameter_types and adding result_type to the front - works like a charm!Plutonian

© 2022 - 2024 — McMap. All rights reserved.