Skip to content

Instantly share code, notes, and snippets.

@timothyqiu
Created October 8, 2013 01:26
Show Gist options
  • Save timothyqiu/6877974 to your computer and use it in GitHub Desktop.
Save timothyqiu/6877974 to your computer and use it in GitHub Desktop.
一次性取得任意层次的字典值 http://timothyqiu.com/archives/variadic-template-practice/
#include <algorithm>
#include <iostream>
#include <map>
#include <unordered_map>
// MapTraits<MapType, KeyType1, KeyType2, KeyType3...>
// ---------------------------------------------------
// 连续使用 KeyType1, KeyType2, KeyType3... 对 MapType 进行取 Value 操作后的信息
template <typename MapType, typename KeyType, typename... KeyTypes>
struct MapTraits
{
typedef typename MapTraits<typename MapType::mapped_type, KeyTypes...>::mapped_type mapped_type;
};
template <typename MapType, typename KeyType>
struct MapTraits<MapType, KeyType>
{
typedef typename MapType::mapped_type mapped_type;
};
// GetMapValue(map, key1, key2, key3...)
// -------------------------------------
// 连续使用 key1, key2, key3... 对 map 进行取 Value 操作
template <typename MapType>
auto GetMapValue(MapType const& map, typename MapType::key_type const& key)
-> typename MapType::mapped_type
{
return map.at(key);
}
template <typename MapType, typename... MoreKeyTypes>
auto GetMapValue(MapType const& map, typename MapType::key_type const& key,
typename MapType::mapped_type::key_type const& anotherKey, MoreKeyTypes... moreKeys)
-> typename MapTraits<typename MapType::mapped_type, typename MapType::mapped_type::key_type, MoreKeyTypes...>::mapped_type
{
return GetMapValue(map.at(key), anotherKey, moreKeys...);
}
int main()
{
// 用于缓解眼花缭乱感
#define MAP_LITERAL(...) { __VA_ARGS__ }
// 一个简单的一对一映射
std::map<std::string, std::string>
simple_dict = MAP_LITERAL({"Hello", "World"});
// 我勒个去映射居然这么麻烦映射
std::map<std::string,
std::map<unsigned long,
std::unordered_map<std::string,
int>>>
nested_dict = MAP_LITERAL( { "x", MAP_LITERAL( { 108, MAP_LITERAL( { "a", 10 } ) },
{ 256, MAP_LITERAL( { "b", 20 } ) } ) });
auto value1 = GetMapValue(simple_dict, "Hello");
std::cout << value1 << std::endl;
auto value2 = GetMapValue(nested_dict, "x", 108, "a");
std::cout << value2 << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment