C++ - 根据上下文实例化派生类
假设我有 200 个从类派生的名为 class1、class2 等的类,以及一个 1 到 200 之间的整数。有没有一种方法可以根据我的整数值具体实例化其中一个派生类?显然我可以手动检查每个值,但我想知道 C++ 中是否有更灵活的东西
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? Obviously I could just manually check for every value but I am wondering is there is anything in C++ that is more flexible
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须对整数进行切换,并实例化特定的类。如果你有这个
int
->程序中其他地方的class
逻辑,您可以考虑使用编译时映射来表示它。查看 Boost.MPL,特别是boost::mpl::map
。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. Look at Boost.MPL, specificallyboost::mpl::map
.这可能只是做同样事情的更长的方法,但是你可以为每个派生类都有一个工厂方法,就像这样......
然后定义这些函数的数组
然后,你可以做
如果你试图摆脱为每个类编写代码,这对您没有帮助,但如果问题是在运行时确定要基于整数创建哪个类,那么这就可以了。
您可能还想使用标准集合类型而不是 C 样式数组。
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...
Then define an array of these functions
Then, you can do
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.
如果您正在寻找一个反射类型系统,您可以在其中查看所有类,然后动态实例化它们,那么不行。您可以在运行时对象上使用 typeid 来查看它们是否相同,但我相信它的行为是实现定义的。
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.
如果您可以模板化您的类,即命名它们,
而不是
使用编译时或运行时数据结构来选择适当的类。
If you can template your class, i.e. name them
instead of
you can use compile-time or run-time data structures to select the appropriate class.