有没有办法从包含类名的字符串中实例化对象?

Is there a way to instantiate objects from a string holding their class name? (有没有办法从包含类名的字符串中实例化对象?)
本文介绍了有没有办法从包含类名的字符串中实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件:Base.h

I have a file: Base.h

class Base;
class DerivedA : public Base;
class DerivedB : public Base;

/*etc...*/

和另一个文件:BaseFactory.h

and another file: BaseFactory.h

#include "Base.h"

class BaseFactory
{
public:
  BaseFactory(const string &sClassName){msClassName = sClassName;};

  Base * Create()
  {
    if(msClassName == "DerivedA")
    {
      return new DerivedA();
    }
    else if(msClassName == "DerivedB")
    {
      return new DerivedB();
    }
    else if(/*etc...*/)
    {
      /*etc...*/
    }
  };
private:
  string msClassName;
};

/*etc.*/

有没有办法以某种方式将此字符串转换为实际类型(类),这样 BaseFactory 就不必知道所有可能的派生类,并且对每个类都有 if() ?我可以从这个字符串生成一个类吗?

Is there a way to somehow convert this string to an actual type (class), so that BaseFactory wouldn't have to know all the possible Derived classes, and have if() for each one of them? Can I produce a class from this string?

我认为这可以通过反射在 C# 中完成.C++中是否有类似的东西?

I think this can be done in C# through Reflection. Is there something similar in C++?

推荐答案

不,没有,除非你自己做映射.C++ 没有创建类型在运行时确定的对象的机制.不过,您可以使用地图自己进行映射:

Nope, there is none, unless you do the mapping yourself. C++ has no mechanism to create objects whose types are determined at runtime. You can use a map to do that mapping yourself, though:

template<typename T> Base * createInstance() { return new T; }

typedef std::map<std::string, Base*(*)()> map_type;

map_type map;
map["DerivedA"] = &createInstance<DerivedA>;
map["DerivedB"] = &createInstance<DerivedB>;

然后你就可以了

return map[some_string]();

获取新实例.另一个想法是让类型自行注册:

Getting a new instance. Another idea is to have the types register themself:

// in base.hpp:
template<typename T> Base * createT() { return new T; }

struct BaseFactory {
    typedef std::map<std::string, Base*(*)()> map_type;

    static Base * createInstance(std::string const& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;
        return it->second();
    }

protected:
    static map_type * getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order 
        if(!map) { map = new map_type; } 
        return map; 
    }

private:
    static map_type * map;
};

template<typename T>
struct DerivedRegister : BaseFactory { 
    DerivedRegister(std::string const& s) { 
        getMap()->insert(std::make_pair(s, &createT<T>));
    }
};

// in derivedb.hpp
class DerivedB {
    ...;
private:
    static DerivedRegister<DerivedB> reg;
};

// in derivedb.cpp:
DerivedRegister<DerivedB> DerivedB::reg("DerivedB");

您可以决定为注册创建一个宏

You could decide to create a macro for the registration

#define REGISTER_DEC_TYPE(NAME) 
    static DerivedRegister<NAME> reg

#define REGISTER_DEF_TYPE(NAME) 
    DerivedRegister<NAME> NAME::reg(#NAME)

不过,我确信这两个名字有更好的名字.在这里使用可能有意义的另一件事是 shared_ptr.

I'm sure there are better names for those two though. Another thing which probably makes sense to use here is shared_ptr.

如果你有一组没有共同基类的不相关类型,你可以给函数指针一个返回类型 boost::variant 代替.就像如果你有一个类 Foo、Bar 和 Baz,它看起来像这样:

If you have a set of unrelated types that have no common base-class, you can give the function pointer a return type of boost::variant<A, B, C, D, ...> instead. Like if you have a class Foo, Bar and Baz, it looks like this:

typedef boost::variant<Foo, Bar, Baz> variant_type;
template<typename T> variant_type createInstance() { 
    return variant_type(T()); 
}

typedef std::map<std::string, variant_type (*)()> map_type;

boost::variant 就像一个联合.它通过查看用于初始化或分配给它的对象来知道其中存储的是哪种类型.在此处查看其文档.最后,使用原始函数指针也有点陈旧.现代 C++ 代码应该与特定的函数/类型分离.您可能需要查看 Boost.Function 寻找更好的方法.它看起来像这样(地图):

A boost::variant is like an union. It knows which type is stored in it by looking what object was used for initializing or assigning to it. Have a look at its documentation here. Finally, the use of a raw function pointer is also a bit oldish. Modern C++ code should be decoupled from specific functions / types. You may want to look into Boost.Function to look for a better way. It would look like this then (the map):

typedef std::map<std::string, boost::function<variant_type()> > map_type;

std::function 也将在 C++ 的下一个版本中可用,包括 std::shared_ptr.

std::function will be available in the next version of C++ too, including std::shared_ptr.

这篇关于有没有办法从包含类名的字符串中实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)