boost::mpl::for_each without instantiating
Asked Answered
H

2

10

Taking the following example, I wonder whether there is an alternative to boost::mpl::for_each, which does call a Functor without any arguments.

#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>

struct EasyFixEngineA { static const char* const name() { return "a"; } };
struct EasyFixEngineB { static const char* const name() { return "b"; } };

struct Registrator {
    // Would prefer a template<class T> void operator()()
    template<class T> void operator()(T t) {
        RegisterInFactory<EasyFixEngine, T> dummy(T::name());
    }
};

// ...
typedef boost::mpl::vector<EasyFixEngineA,EasyFixEngineB> Engines;
boost::mpl::for_each<Engines>(Registrator());

It seems like for_each is default-instantiating the types.

Hebdomad answered 25/7, 2014 at 10:59 Comment(0)
C
13

Use boost::type and mpl::_ to create an MPL lambda that transforms each type in the list before instantiating the elements and calling the function, like this:

mpl::for_each<Engines, boost::type<mpl::_> >(Registrator());

Registrator should look something like this:

struct Registrator
{
  template<typename T>
  void operator()(boost::type<T>) const
  {
      RegisterInFactory<EasyFixEngine, T> dummy(T::name());
  }
};

Hope that helps.

Citral answered 25/7, 2014 at 17:2 Comment(0)
B
0

You should use the three parameter for_each:

mpl::for_each<Engines,mpl::single_view>(Registrator())

Then the instances you get will be of single_view.

Battle answered 25/7, 2014 at 11:41 Comment(2)
The code sadly does not work. I also cannot find any example how to properly use single_view.Hebdomad
Besides it seems like you are passing a partial typed template, only.Hebdomad

© 2022 - 2024 — McMap. All rights reserved.