gpt4 book ai didi

c++ - 如何继承类型列表,然后调用继承成员列表中的成员?

转载 作者:可可西里 更新时间:2023-11-01 16:36:33 26 4
gpt4 key购买 nike

我有一组具有以下结构的类:

class U
{
public:
explicit U(int) { ... }
U() {...}
Init(int) {...}
};

我需要能够将这些类中的 1 个或多个组合成 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.
}
};

我认为我需要大量的 mpl,但我并不是很擅长。我想做的事情可行吗?代码示例会很棒。

我的错误: 忘了说我不能使用 C++11 功能。我正在寻找 MPL 解决方案。

最佳答案

好吧,Boost.MPL 包含元函数 inheritinherit_linearly 您可以将它们与 for_each 组合以获得第二个变体(带有初始化函数) .或者只使用 boost::mpl::fold 和自定义元函数:

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)
{ }
};

使用示例:

#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);
}

元函数 InheritFrom_IntConstructor 可以泛化为接受任意类型作为构造函数参数,我不确定是否可以泛化为接受任意数量的参数。

关于c++ - 如何继承类型列表,然后调用继承成员列表中的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com