简体   繁体   English

C ++-根据上下文实例化派生类

[英]C++ - Instantiate derived class depending on context

let's say I have 200 classes named class1, class2, etc derived from class, and a integer between 1 and 200. Is there a way to instanciate specifically one of the derived class depending on the value of my integer? 假设我有200个从该类派生的名为class1,class2等的类,以及一个介于1到200之间的整数。是否有一种方法可以实例化一个派生类中的一个,具体取决于我的整数值? Obviously I could just manually check for every value but I am wondering is there is anything in C++ that is more flexible 显然,我可以手动检查每个值,但我想知道C ++中是否有任何更灵活的东西

You will have to do a switch on your integer, and instantiate the specific class. 您将必须对整数进行切换,并实例化特定的类。 If you have this int -> class logic somewhere else in your program, you could consider representing it with a compile-time map. 如果您在程序中的其他位置具有int > class逻辑,则可以考虑使用编译时映射表示它。 Look at Boost.MPL, specifically boost::mpl::map . 看一下Boost.MPL,特别是boost::mpl::map

This may be just a longer way of doing the same things, but you could have a factory method for each derived class like so... 这可能只是做相同事情的一种更长的方法,但是您可以为每个派生类提供一个工厂方法,就像这样……

std::auto_ptr<BaseClass> createClass0()
{
    return std::auto_ptr<BaseClass>(new Class0());
}

Then define an array of these functions 然后定义这些函数的数组

typedef std::auto_ptr<BaseClass> (*pt2Creator)();
pt2Creator creators[] = {createClass0, ...};

Then, you can do 那你就可以

std::auto_ptr<BaseClass> createClass(int n)
{
   return creators[n]();
}

If you were trying to get out of having to write code for each class, this doesn't help you, but if the problem is figuring out at run-time which class to create based on an integer, this will do it. 如果您试图摆脱为每个类编写代码的麻烦,那么这无济于事,但是如果问题是在运行时确定根据整数创建哪个类,则可以这样做。

You may also want to use a standard collection type rather than a C-style array. 您可能还想使用标准的集合类型而不是C样式的数组。

If you are looking for a reflection type system where you can see all of classes and then instantiate them dynamically no. 如果您正在寻找一个反射类型的系统,可以在其中看到所有类,然后动态实例化它们。 You can use typeid on runtime objects to see if they are the same but I believe its behavior is implementation defined. 您可以在运行时对象上使用typeid来查看它们是否相同,但我相信其行为是实现定义的。

If you can template your class, ie name them 如果可以为您的班级做模板,即为他们命名

template <int I> class Foo;

instead of 代替

class FooI

you can use compile-time or run-time data structures to select the appropriate class. 您可以使用编译时或运行时数据结构来选择适当的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM