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

标签 c++ templates boost metaprogramming boost-mpl

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

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/

相关文章:

c++ - 将 Boost (Spirit) 与 g++(以及后来的 Eclipse)一起使用

c++ - Boost矩阵的iterator1和iterator2是什么,如何使用?

c++ - template<typename T...>func(T&&..arg) 和 template<typename TT, typename... T>func(T&&..args);为什么 l-vals 转到第二个而 r-vals 无法编译?

c++ - 多个枚举是否由换行符分隔然后逗号总是可移植的?

c++ - 如何设置:hover on QMenu?

c++ - 重载赋值运算符 - 多态容器

c++ - 有没有办法获得具有不同函数名称的通用/模板化功能?

javascript - 我如何渲染 Bootstrap 切换

c++ - Boost.Log,在文件名或配置文件的目标值中使用自定义属性

c++ - 将 std::bind 创建的对象传递给函数的正确方法是什么?