自动创建继承实例

时间:2013-07-22 09:25:59

标签: c++ inheritance boost c++11 metaprogramming

我在 c ++ 11 boost 中进行编程,我正在尝试实现某种类型的框架,其中有人只需要继承类Base < / strong>并实施方法(),这可能取决于其他继承。 然后应该在main函数中自动创建这些继承,而不需要程序员进行任何修改。

class Base
{
public:
   virtual void method() = 0;
}

class A : public Base
{
public:
   static int state = 0;

   void method()  //
   {
      //do something with B
      A::state = B::state * 3;
   }
}

class B : public Base
{
public:
   static int state = 0;

   void method() //
   {
      //do something with A
      B::state = A::state * 2;
   }
}

int main()
{

//Access to an Array containing ONE pointer to each Inheritance

vector<Base*> inheritancesOfBase;
inheritancesOfBase.push_back(new A); // <- should be done automatically 
inheritancesOfBase.push_back(new B); // <- should be done automatically 

//PSEUDOCODE
for_each(base* pInh in inheritancesOfBase)
{

    pInh->method();
    clones.push_back(pInh->clone());

}


return 0;
}

我认为这应该可以用一些花哨的元编程来实现,但是如何?

编辑:澄清

2 个答案:

答案 0 :(得分:0)

首先:您的代码无法编译,因为您错过了静态的定义。您需要在代码中添加int A::state = 0(或类似代码),并为B::state添加相同内容。

其次,无法自动创建A和B对象,因为编译器无法知道您对代码的意图是什么。因此,您至少需要在main中声明A和B对象。例如。编译器应该如何知道,您只需要一个A和五个B对象?所以你必须向编辑说明你的意图:

int main(void)
{
    A myA;
    B myBArray[5];
    vector<shared_ptr<Base>> myABCollection;
}

答案 1 :(得分:0)

所以,我们有类似

的东西
class Base
{
public:
   virtual void method() = 0;
};

(不要忘记课后的分号) 和许多子类,而不仅仅是显示的AB

我们希望main执行类似

的操作
for(Base & item : instances)
{
    item.method();
}

您可以创建一个工厂,跟踪其在vector<shared_ptr<Base>>中创建的内容,并在询问时返回instances
这解决了问题的一半。如果你想找到派生自Base的所有类,给定C ++没有反射,我看不出你是怎么做的。你可以使用clang拼凑一些东西并以这种方式生成一些代码。 RecusiveASTVisitor可能会有所帮助。