I've been looking for a class in MPL that will create a function object from a sufficiently well-behaved MPL metafunction class. I hand-rolled this implementation:
template <class Lambda, class Result>
struct functor
{
typedef Result result_type;
template <typename Type>
Result operator()( Type )
{ return Lambda::template apply<Result>::type::value; }
};
A usage example would be
Foo foo;
return functor< boost::mpl::always<boost::mpl::int_<5> >, int >( foo );
as a glorified version of writing return 5
.
As this operation seems pretty basic, I'd have thought there is already a similar class in MPL, but a search of the documentation didn't yield anything for me. Am I missing something?
I don't think there is such a class in Boost.MPL, since they focus exclusively on compile-time computations. This kind of wrapper would rather be held in Boost.Fusion, which aims at making the link between compile and runtime entities, but I did not found anything.
I think you will have to use your own implementation, which seems alright at a glance (even though I would rather use mpl::apply
to handle placeholder expressions). I think you could also omit the return type, since it can be deduced from the lambda.
Here is an alternate implementation using apply
and deducing the return type from the lambda:
template < typename Lambda >
struct functor
{
template < typename Type >
typename boost::mpl::apply< Lambda, Type >::type::value_type
operator()( Type )
{
return boost::mpl::apply< Lambda, Type >::type::value;
}
};
// sample use:
int main()
{
boost::mpl::int_<5> five;
std::cout << functor< boost::mpl::identity< boost::mpl::_ > >()( five );
// Output "5"
}