gpt4 book ai didi

c++ - 压缩 `std::tuple` 和可变参数

转载 作者:可可西里 更新时间:2023-11-01 16:01:12 25 4
gpt4 key购买 nike

我有以下类(class):

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 以便它分配给 maps 中的每个 std::map 并使用它匹配的键调用?

例如,如果我有

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);

最佳答案

#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)... });
}
};

DEMO

关于c++ - 压缩 `std::tuple` 和可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37390060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com