Search code examples
c++templatesdictionarymovevariadic-templates

emplacing object with variadic constructor into map


I have a movable (but not copyable) type with a variadic template constructor

struct foo
{
  std::string a,b,c;
  foo(foo const&)=delete;
  foo(foo&&)=default;
  template<typename...T>
  for(T&&...);
};

and I want to add it into a map:

template<typename...T>
void add_foo(std::map<std::string,foo>&map, const char*name, T&&...args)
{
  map.emplace(std::piecewise_construct,      // how? perhaps like this?
              std::forward_as_tuple(name),   //   no:
              std::forward_as_tuple(args));  //   error here
}

Solution

  • std::forward_as_tuple() takes a pack, so you can simply expand args using ...:

    map.emplace(std::piecewise_construct,
                std::forward_as_tuple(name),
                std::forward_as_tuple(args...));