【发布时间】:2015-03-10 08:53:32
【问题描述】:
是否可以定义(以简单的方式,可能重复使用 std 容器)“关联 std::tuple”,或者换句话说,“变量 std::map”。
类似这样的(这个界面只是说明,欢迎其他可能的界面):
AssociativeTuple<std::string> at; // std:string is the key type
at.insert<float>("my_float", 3.14); // 1.
at.insert<int>("my_int", 42);
at.insert<bool>("my_bool", true);
at.insert<int>("xyz", 0);
at.insert<std::string>("my_string", "hello world!");
assert(get(at, "my_float") == 3.14); // 2.
assert(get(at, "my_int") == 42);
assert(at["my_string"] == "hello world!"); // 3.
assert(std::is_same<at.type_of("my_float")::type, float>) // 4.
for (auto it : at) { std::cout << it.first << " = " << it.second; } // 5.
其他理想的约束:
- 值/键集仅在运行时已知。但是在编译时,用户知道(值的类型)和键之间的关系。例如,用户在编译时知道
"my_float"将是float。换句话说,可能的键集合是固定的,并且对应于键的值的类型在编译时是已知的。编译时不知道的是“是否”将密钥插入容器内。当然,映射值的值在编译时是未知的。 - 访问性能,
get应该很快 - 用户不必记住与键关联的类型
我真正的问题只是float/int/bool 类型的值(我正在做的是将所有内容存储在std::map<std::string, float> 中并在必要时转换为int),但是一个通用的解决方案是可取的。在我的真实情况下,密钥总是std::string。
【问题讨论】:
-
std::map<std::string, variant>不能解决您的问题吗? -
@JBL: 第4行怎么办?
-
我已经更好地解释了编译时已知的内容
-
我们在谈论多少个不同的键?
-
您对第 1 点的编辑是否与第 3 点相矛盾?
标签: c++ c++11 containers variadic-templates