本文介绍了元编程:在boost mpl :: vector中从每个类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从boost mpl :: vector中包含的一组类中继承.这可能吗?

I wish to inherit from a set of classes contained in a boost mpl::vector. Is this possible?

具体来说,我希望将test扩展为以mpl :: vector形式传递的任意多个模板参数.

Specifically, I wish to extend test for arbitrary many template parameters, passed as a mpl::vector.

template<class T>
struct Slice
{
public:
  virtual void foo(T v) const = 0;
};

struct A{};
struct B{};

template <class T1, class T2>
struct test : public Slice<T1>, public Slice<T2>
{
  void foo(T1 a) const {std::cout<<"A"<<std::endl;}
  void foo(T2 b) const {std::cout<<"B"<<std::endl;}
};

如果我知道只有两个参数,那么我可以简单地写:

If I know there are only two parameters then I can simply write:

template <class mpl_vector_t >
struct test : public Slice<typename mpl::at<mpl_vector_t,mpl::int_<0> >::type >, 
          public Slice<typename mpl::at<mpl_vector_t,mpl::int_<1> >::type >
{
  typedef typename mpl::at<mpl_vector_t,mpl::int_<0> >::type T1;
  typedef typename mpl::at<mpl_vector_t,mpl::int_<1> >::type T2;

  void foo(T1 a) const {std::cout<<"A"<<std::endl;}
  void foo(T2 b) const {std::cout<<"B"<<std::endl;}
};

是否可以对任意mpl :: vector执行此操作?

Is is possible to do this for an arbitrary mpl::vector?

我的测试程序如下:

int
main  (int ac, char **av)
{
  A a;
  B b;
  // test<A,B> t; //original
  test<mpl::vector<A,B> > t;  //mpl::vector with 2 elements
  Slice<A>* Sa = &t;
  Slice<B>* Sb = &t;
  Sa->foo(a);
  Sb->foo(b);
}

推荐答案

您要使用 mpl :: inherit_linearly

这篇关于元编程:在boost mpl :: vector中从每个类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 22:01