C++服务提供商

Sea*_*mes 1 c++ service dictionary

我一直在学习C++,来自C#,我已经习惯使用服务提供者:基本上是一个Dictionary <Type,object>.不幸的是,我无法弄清楚如何在C++中做到这一点.所以问题基本上是:

  1. 我如何在C++中创建字典.

  2. 我如何使用'Type',据我所知,C++中没有'Type'.

  3. 与上面相同,但使用'object'.

谢谢!

Ecl*_*pse 5

我假设您正在尝试将类型映射到单个对象实例.你可以尝试这些方面:

#include <typeinfo>
#include <map>
#include <string>
using namespace std;

class SomeClass
{
public:
    virtual ~SomeClass() {} // virtual function to get a v-table
};

struct type_info_less
{
    bool operator() (const std::type_info* lhs, const std::type_info* rhs) const
    {
        return lhs->before(*rhs) != 0;
    }
};

class TypeMap
{
    typedef map <type_info *, void *, type_info_less> TypenameToObject;
    TypenameToObject ObjectMap;

public:
    template <typename T> 
    T *Get () const
    {
        TypenameToObject::const_iterator iType = ObjectMap.find(&typeid(T));
        if (iType == ObjectMap.end())
            return NULL;
        return reinterpret_cast<T *>(iType->second);
    }
    template <typename T> 
    void Set(T *value) 
    {
        ObjectMap[&typeid(T)] = reinterpret_cast<void *>(value);
    }
};

int main()
{
    TypeMap Services;
    Services.Set<SomeClass>(new SomeClass());
    SomeClass *x = Services.Get<SomeClass>();
}
Run Code Online (Sandbox Code Playgroud)

在C++类型中,它们本身并不是第一类对象,但至少类型名称将是唯一的,因此您可以通过它来键入.

编辑:名称实际上并不保证是唯一的,因此请继续使用type_info指针并使用before方法进行比较.