有没有可能(简单地,可能重新使用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