首页 > 解决方案 > 静态映射类到 std::type_index 中的值“表达式必须具有常量值”

问题描述

我正在尝试在 C++ 中构建一个结构,它将类作为键并将整数作为值。我想要这种静态映射,然后我可以在我的程序中使用它来轻松访问与某个类关联的 int。

这是我正在尝试编写的代码:

#include <unordered_map>
#include <typeindex>
#include <typeinfo>
#include "TransformC.h"

// map class -> int
std::unordered_map<std::type_index, int> comp_cols;
// populate map
comp_cols[std::type_index(typeid(TransformC))] = 0;
...

我在 Visual Studio 2017 上,在std::type_index.

我不明白那个错误到底是什么,我不知道是否还有其他方法可以实现我想要实现的目标(可能是一些模板恶作剧在编译时map<Class>用正确的索引替换 a ?)

仅当上面发布的代码在文件范围内时(我在函数范围内没有错误),我才会收到此错误。我不明白为什么在一种情况下存在错误,而在另一种情况下没有。

请帮忙!

标签: c++staticcompile-timetypeidcompile-time-constant

解决方案


推荐阅读