从boost mpl向量注册类型

Registering types from a boost mpl vector

本文关键字:注册 类型 向量 mpl boost      更新时间:2023-10-16
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); 

如何使用boost::mpl自动生成最后3行?我说的自动是指不需要重复3次"相同"行

使用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());

如果T的实例化不适合您的情况,请参见此问题

简短的回答是你不能。

确实有三种不同的东西:-编译时执行(即。元编程),这是用MPL完成的。它们只对类型定义起作用-运行时执行(即。通常的编程),它是普通的c++(此时所有类型都已定义)-变量声明

你想使用MPL(编译时)来生成一些c++代码(变量声明)并做一些运行时(变量初始化)。

也许你想看看boost::fusion (fusion意味着编译时和运行时操作的结合)。如果你在boost::fusion中声明了三个变量,还有三个字符串,那么你可以使用boost::fusion::transform。但我不确定这是不是你想要的