Search code examples
c++boostboost-mpl

Registering types from a boost mpl vector


std::string a= "a";
std::string b= "b";
std::string c= "c";

typedef mpl::vector<EasyFixEngineA,EasyFixEngineB,EasyFixEngineC> vecType;

RegisterInFactory<EasyFixEngine, mpl::at_c<vecType,0>::type>    registerA( a); 
RegisterInFactory<EasyFixEngine, mpl::at_c<vecType,1>::type,>   registerB( b);  
RegisterInFactory<EasyFixEngine, mpl::at_c<vecType,2>::type>    registerC( c); 

How can I generate automatically the last 3 lines by using boost::mpl ? By automatically I mean don't have to repeat 3 times the "same" line


Solution

  • One possibility utilizing mpl::for_each:

    #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 {
        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());
    

    If the instantiation of T isn't suitable in your case, see this question.