2013-07-22 47 views
1

我在C++ 11升压编程的情况下,我想实现某种框架,其中一个人只需要从Base类继承,并实现()方法 ,这可能取决于其他继承。 然后应该在主函数中自动创建这些继承,而不需要程序员进行任何修改。自动创建继承

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

我认为这应该是可以与一些花式元编程,但如何?

编辑:澄清

+0

目前尚不清楚你真正想要什么 - 在运行时创建一些As和Bs,或者在运行时创建新类的类型(使用编译时元编程...?) – doctorlove

+0

最后,我想有一个数组包含每个继承的一个实例(或指针)。 – Paul

+0

我想我已经找到了解决我的问题[这里] [1] [1]:http://stackoverflow.com/questions/17410942/c-automatic-instantiation-of-derived-classes – Paul

回答

0

首先:当你缺少的静把定义您的代码将无法编译。您需要在代码中添加int A::state = 0(或类似),并在B::state中添加相同的代码。

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

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

它也不会编译因为它缺少分类后的分号 – doctorlove

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可能会有所帮助。

+0

这正是我的意思。 – Paul

+0

基本上我想避免的是实现新方法的程序员需要在项目的其他地方传播其存在......也许我正在运行在我的项目的基本设计问题中? – Paul

+0

我不清楚你的意思 - 这正在变成聊天。也许我们应该把它聊天 – doctorlove