有没有办法从一个字符串实例化对象的类名? [英] Is there a way to instantiate objects from a string holding their class name?

查看:172
本文介绍了有没有办法从一个字符串实例化对象的类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件: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不必知道所有可能的Derived类,并有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

如果你有一组不相关的类型没有共同的基类,你可以给函数指针一个返回类型 boost ::变体< A,B,C,D ... ...> 。如果你有一个类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;

A 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.

这篇关于有没有办法从一个字符串实例化对象的类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆