I have the following 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;
}
};
How would I implement foo
so that it assigns to each std::map
in maps
gets called with it matching key?
For example, if I have
C<int, int, float, std::string> c;
and I called
c.foo(1, 2, 3.3, "qwerty")
then c.maps
should be equivalent to
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
If you have a compiler that supports C++17 fold expressions then you could have the following simple variadic expansion scheme:
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)...);
}
};
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With