在 C++ 中,给定一个字符串向量,如何在编译时填充映射?

In C++, how do I populate a map at compile-time, given a vector of strings?

给定一个在编译时已知的字符串向量(并说出它们应该映射到的一些数字),我希望在编译时创建这样一个映射(f.e。unordered_map) -时间。目标是快速启动并在运行时执行查找。举个例子:

enum category {fruit, vegetable};
const std::vector<std::string> fruits = {"apple", "pear", "orange"};
const std::vector<std::string> vegetables = {"cucumber", "zucchini", "tomato"};
const std::unordered_map<std::string, category> lookup_category = // ?

但是,constexpr 禁止使用非文字。模板化是一种解决方案,但实施和维护起来非常令人头疼。

C++(17?) 在 STL 中有什么东西可以帮助我在编译时构建这样的映射吗?

编译时没有 vectorstringmap。事实上,具有非平凡析构函数的 class 类型的对象不能在 constexpr 上下文中使用。所以这根本做不到。

从 c++20 开始,您可以拥有非平凡的析构函数,因此原则上这是可能的。据我所知,在 constexpr 上下文中只有 vectorstring 可用,即便如此,它们分配的所有存储必须在 运行-时间。所以你甚至不能在编译时有一个 vectorstring 你也可以在 运行-time.

从 c++20 开始,您可以保证 vectorstring,或 map 在程序加载时被 初始化 不过时间,使用 keyword constinit.

如果您只想对 const map 进行复杂的初始化,您甚至可以在 c++20 之前使用 IIILE(立即调用初始化 lambda 表达式)来完成。例如

const map<string, int> m = [] {
  map<string,int> x; // construct a map ...
  x["hi"] = 42;  // populate it
  return x;// return it
}();   // and call the expression straight away.