我有以下类:
template<typename... Tkeys> class C { public: std::tuple<std::unordered_map<Tkeys,int>... > maps; // Not real function: void foo(Tkeys... keys) { maps[keys] = 1; } };
我如何实现foo,以便它分配给映射中的每个std :: map,使用匹配的key来调用它?@H_403_5@
例如,如果我有@H_403_5@
C<int,int,float,std::string> c;
我打来电话@H_403_5@
c.foo(1,2,3.3,"qwerty")
那么c.maps应该等同于@H_403_5@
m1 = std::map<int,int>() m1[1] = 1; m2 = std::map<int,int>() m2[2] = 1; m3 = std::map<float,int>() m3[3.3] = 1; m4 = std::map<std::string,int>() m4["qwerty"] = 1; c.maps = std::make_tuple(m1,m2,m3,m4);
解决方法
#include <unordered_map> #include <utility> #include <tuple> #include <cstddef> template <typename... Tkeys> class C { public: std::tuple<std::unordered_map<Tkeys,int>... > maps; template <typename... Args> void foo(Args&&... keys) { foo_impl(std::make_index_sequence<sizeof...(Args)>{},std::forward<Args>(keys)...); } private: template <typename... Args,std::size_t... Is> void foo_impl(std::index_sequence<Is...>,Args&&... keys) { using expand = int[]; static_cast<void>(expand{ 0,( std::get<Is>(maps)[std::forward<Args>(keys)] = 1,void(),0)... }); } };