我有以下课程:
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
中的每个maps
分配,并使用匹配键进行调用?
例如,如果我有
C<int, int, float, std::string> c;
我打电话给
c.foo(1, 2, 3.3, "qwerty")
然后c.maps
应该等同于
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);
答案 0 :(得分:7)
#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)... });
}
};
答案 1 :(得分:3)
如果您的编译器支持C ++ 17折叠表达式,那么您可以使用以下简单的可变参数扩展方案:
template<typename... Tkeys>
class C {
template<typename... Args, std::size_t... I>
void foo_helper(std::index_sequence<I...>, Args&& ...args) {
((std::get<I>(maps)[std::forward<Args>(args)] = 1), ...);
}
public:
std::tuple<std::unordered_map<Tkeys, int>... > maps;
void foo(Tkeys... keys) {
foo_helper(std::index_sequence_for<Tkeys...>{}, std::forward<Tkeys>(keys)...);
}
};
答案 2 :(得分:0)
对于当前的C ++(2014),只需使用带有标记函数的经典模式:
public:
void foo(Tkeys... keys) {
foo_range<0>(keys...);
}
private:
template <std::size_t I, typename F, typename... N>
void foo_range(F first, N... next) {
std::get<I>(maps)[first] = 1;
foo_range<I + 1>(next...);
}
template <std::size_t I>
void foo_range() {
static_assert(I == sizeof...(Tkeys), "That should be sentinel");
}