我喜欢使用std::tuple
构建“地图”,键是std::string
,值是任何类型,其定义如下:
template<typename... Args>
using Map = std::tuple<std::pair<std::string, Args>...>;
而且我有一个函数MakeMap
,它接受可变参数,将参数转换为Map
并返回它:
template<typename... Args>
Map<???> MakeMap(Args&&... args) {
???
}
并且我希望MakeMap
的参数采用std::string, type1, std::string, type2, ...
格式(例如键和值):
auto map = MakeMap("key1", 42, "key2", "hello world"); // OK
auto map = MakeMap(1, 2); // expects compiling error
auto map = MakeMap("key1", 42, "key2"); // expects compiling error
因此,如何实现函数MakeMap
(在C ++ 11中),以使上述调用语法起作用?
谢谢。
以下是实现此目的的方法(进行了一些更改)