【问题标题】:emplacing object with variadic constructor into map将具有可变参数构造函数的对象放入映射中
【发布时间】:2014-04-25 00:09:50
【问题描述】:

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

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
}

【问题讨论】:

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


    【解决方案1】:

    std::forward_as_tuple() 需要一个包,因此您可以使用 ... 简单地扩展 args

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

    【讨论】:

      【解决方案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");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-24
        • 2019-06-04
        • 1970-01-01
        • 1970-01-01
        • 2013-01-14
        • 2023-03-15
        相关资源
        最近更新 更多