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

发布于 2024-12-12 05:08:44 字数 124 浏览 0 评论 0原文

假设我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

噩梦成真你也成魔 2024-12-19 05:08:44

您必须对整数进行切换,并实例化特定的类。如果你有这个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, specifically boost::mpl::map.

流心雨 2024-12-19 05:08:44

这可能只是做同样事情的更长的方法,但是你可以为每个派生类都有一个工厂方法,就像这样......

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

然后定义这些函数的数组

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

然后,你可以做

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

如果你试图摆脱为每个类编写代码,这对您没有帮助,但如果问题是在运行时确定要基于整数创建哪个类,那么这就可以了。

您可能还想使用标准集合类型而不是 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...

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.

执手闯天涯 2024-12-19 05:08:44

如果您正在寻找一个反射类型系统,您可以在其中查看所有类,然后动态实例化它们,那么不行。您可以在运行时对象上使用 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.

愛放△進行李 2024-12-19 05:08:44

如果您可以模板化您的类,即命名它们,

template <int I> class Foo;

而不是

class FooI

使用编译时或运行时数据结构来选择适当的类。

If you can template your class, i.e. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文