mercredi 23 octobre 2019

Build a specific tuple from a function's variadic argument

I like to build a "map" using std::tuple, the key is std::string, the value is any type, it's defined as following:

template<typename... Args>
using Map = std::tuple<std::pair<std::string, Args>...>;

And I have a function MakeMap, which accepts variadic arguments, to turn the arguments into a Map and returns it:

template<typename... Args>
Map<???> MakeMap(Args&&... args) {
    ???
}

And I'd like the arguments of MakeMap to be in std::string, type1, std::string, type2, ... format (a key followed by a value), for example:

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

So, how to implement the function MakeMap (in C++11), to make the above call syntax work?

Thanks.

Aucun commentaire:

Enregistrer un commentaire