在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
Is it possible to create a new instance of base class based on a given identifier and vice versa in C++
我有一个基类和多个子类对其进行扩展。我的目标是使用C++创建一个基于标识符的子类的新实例,反之亦然。我使用了一个类似于这样的切换用例语句:
std::shared_ptr<base> create(int id)
{
std::shared_ptr<base> p;
switch (id) {
case 0:
p = std::make_shared<derived1>();
break;
case 1:
p = std::make_shared<derived2>();
break;
default:
throw;
}
return p;
}
但我想要一种更优雅的方法,反之亦然。以下是我用Java编码的目标的工作实现:
static BiMap<Integer, Class<? extends Base>> map = HashBiMap.create();
static {
map.put(0, Derived1.class);
map.put(1, Derived2.class);
}
static Base createInstance(int id) throws IllegalAccessException, InstantiationException {
return map.get(id).newInstance();
}
static int getId(Base instance) {
return map.inverse().get(instance.getClass());
}
提前谢谢!
C++不像Java那样有元类。因此,与Java代码最接近的C++等价物看起来是这样的:
#include <map>
#include <memory>
class Base
{
public:
...
virtual int getId() const = 0;
};
class Derived1: public Base
{
public:
...
int getId() const override { return 0; }
};
class Derived2: public Base
{
public:
...
int getId() const override { return 1; }
};
...
using createFunc = std::shared_ptr<Base>(*)();
static std::map<int, createFunc> myMap
{
{0, []() -> std::shared_ptr<Base> { return std::make_shared<Derived1>(); }},
{1, []() -> std::shared_ptr<Base> { return std::make_shared<Derived2>(); }}
...
};
static std::shared_ptr<Base> createInstance(int id)
{
auto iter = myMap.find(id);
if (iter == myMap.end())
throw ...;
return iter->second();
}
static int getId(Base* instance)
// or: static int getId(std::shared_ptr<Base> &instance)
{
return instance->getId();
}
实时演示
我会有一个类似_getId()
的虚拟函数。然后,您可以让每个派生类返回其唯一标识符:
class base {
...
virtual int _getId() = 0;
};
class derived1: public base {
...
int _getId() { return 1; }
};
...
所以你的静态基础getId()
可能看起来像:
static int getId(base *instance) {
return instance->_getId();
}
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 与简单地创建派生类指针相比,将基类绑定到派生类有什么优点?
- 从引用创建指向基类的智能指针
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- 在基类中创建派生类的对象
- 一般函数中类的概括为基类创建对象代码
- 创建并编译基类以在其他 C++ 项目 (ROS) 中使用
- 如何使用 CRTP 创建具有基类的可选模板参数
- 如何为基类通用类型创建向量以使用具体类型元素
- 如何为抽象基类创建模板实例化?
- 将使用基类 Ctor创建的对象转换为派生类
- CRTP - 是否可以创建一个抽象基类?
- 动态创建一个继承的类,使用STD :: MAP使用基类指针访问
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 如何从现有基类对象创建派生类对象
- 是否可以在C++中声明基类,以便只能通过创建函数创建从它派生的类
- 说明如何通过基类创建派生类的对象(虚拟析构函数概念)
- 从基类创建对象并将其添加到派生类数组