1

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?

1
  • On reading the clarifying comments, Boost Fusion might be what you are looking for. It does this: a fusion of meta and runtime programming (note that Fusion comes with it's own Sequence (and derived) Concepts. However, MPL Sequences are adapted Commented Nov 23, 2011 at 14:31

1 Answer 1

1

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

@sehe: You are right, I forgot for_each (I must admit that I never had to use it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.