Arm*_*yan 9 c++ templates boost metaprogramming boost-mpl
我有一组具有以下结构的类:
class U
{
public:
explicit U(int) { ... }
U() {...}
Init(int) {...}
};
Run Code Online (Sandbox Code Playgroud)
我需要能够将这些类中的一个或多个组成一个类X.伪代码:
template<class TypeSequence>
class X that derives publicly from all the classes in TypeSequence
{
X(int): all bases are initialized with the integer passed
{}
//if the above constructor is impossible, then the following will do as well:
X(int)
{
Call Init on all bases and pass the given int to them.
}
};
Run Code Online (Sandbox Code Playgroud)
我想我需要很多mpl,但我并不擅长它.我想做什么可行?代码示例会很棒.
我的错误:忘记提及我不能使用C++ 11功能.我正在寻找MPL解决方案.
好吧,Boost.MPL包含元函数inherit,inherit_linearly你可以将它们组合起来for_each获得第二个变量(使用init函数).或者使用just boost::mpl::fold和custom元函数:
struct Null_IntConstructor
{
Null_IntConstructor(int) { }
};
struct InheritFrom_IntConstructor_Folder
{
template<typename T1, typename T2>
struct apply
{
struct type : T1, T2
{
type(int x) : T1(x), T2(x) { }
};
};
};
template<typename Bases>
struct InheritFrom_IntConstructor
: boost::mpl::fold<Bases,
Null_IntConstructor,
InheritFrom_IntConstructor_Folder>::type
{
InheritFrom_IntConstructor(int x)
: boost::mpl::fold<Bases,
Null_IntConstructor,
InheritFrom_IntConstructor_Folder>::type(x)
{ }
};
Run Code Online (Sandbox Code Playgroud)
用法示例:
#include <iostream>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/vector.hpp>
struct A
{
A(int x) { std::cout << "A::A " << x << std::endl; }
};
struct B
{
B(int x) { std::cout << "B::B " << x << std::endl; }
};
struct C
{
C(int x) { std::cout << "C::C " << x << std::endl; }
};
int main()
{
InheritFrom_IntConstructor< boost::mpl::vector<A, B, C> >(1);
}
Run Code Online (Sandbox Code Playgroud)
元函数InheritFrom_IntConstructor可以推广为接受任意类型作为构造函数参数,我不确定是否可以推广接受任意数量的参数.