c++ - 以类名作为键的映射

标签 c++ class stl key typename

是否可以以某种方式使用类名作为容器中的键?

我想存储从同一基继承的类的对象。

struct storage {};

struct storagetransform : public storage
{
    vec3 position, rotation;
};

struct storageform : public storage
{
    unsigned int vertex, texture;
};

我有一个嵌套 map 。 ... 应填充特定的类名称,例如 storagetransformstorageform 作为类型或字符串或其他内容。

unordered_map<..., unordered_map<int, storage*> > list;

我想像下面这样访问容器的对象。

list[storagetransform](1337);

这有可能吗?另外有没有更好的方法来解决这个问题?

最佳答案

如果您确实接受像这样访问您的列表:

list[ type_index ( typeid(classname) ) ]

您可以使用 std::type_index 将您的类映射到可索引(可在 std::map 等中使用)对象,并且您可以按如下方式声明您的 std::map

std::map< std::type_index , ... > list;

据我所知,这需要一个符合新 C++ 标准的编译器。

关于c++ - 以类名作为键的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13900469/

相关文章:

c++ - C++ main() 的第三个环境变量参数有什么用?

c++ - 不同的 C++ 模板类型名定义是否意味着相同?

C++ IO 文件流 : writing from one file to another using operator<< and rdbuf()

c++ - 微软 Visual Studio 社区 2017 的 Graphics.h

c++ - 奇怪的段错误

python:实例化模块中的所有子类及其函数输出

c++ - (w)ifstream 是否支持不同的编码

c++ - boost::range 如何使用管道输入在 map 中插入元素

C++:抽象指针的映射似乎正在切片到抽象类

c++ - 如何根据类访问特定的 protected 继承成员?