将具有可变参数构造函数的对象放入map中

时间:2014-04-25 00:09:51

标签: c++ templates map move variadic-templates

我有一个带可变参数模板构造函数的可移动(但不可复制)类型

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

我希望将其添加到地图中:

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
}

2 个答案:

答案 0 :(得分:2)

std::forward_as_tuple()需要一包,因此您只需使用args展开...

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

答案 1 :(得分:2)

您需要解压缩参数:args...

查看 Live On Coliru

#include <string>
#include <map>

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


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
}

int main()
{
    std::map<std::string,foo> m;
    add_foo(m, "a", "b", "c");
}