复制std :: tuple

时间:2017-08-16 01:55:07

标签: c++ stdtuple

我试图将一些值赋给从std :: tuple派生的类。 我想到的第一件事是使用make_tuple,然后使用operator=复制它,但这不起作用。

如果我手动分配了元组的单个值,则没有问题。

所以我写了一小段代码,从项目中提取它,专门测试这一点:

#include <tuple>
template <class idtype>
class Userdata: public std::tuple<idtype, WideString, int>
{
  public:
  /* compile error
  void assign1(const idtype& id, const WideString& name, const int lvl)
  {
    (*this)=std::make_tuple(id, name, lvl);
  }
  */
  void assign2(const idtype& id, const WideString& name, const int lvl)
  {
    (std::tuple<idtype, WideString, int>)(*this)=std::make_tuple(id, name,  lvl);
  }
  void assign3(const idtype& id, const WideString& name, const int lvl)
  {
    std::get<0>(*this)=id;
    std::get<1>(*this)=name;
    std::get<2>(*this)=lvl;
  }
  void print(const WideString& testname) const
  {
    std::cout << testname << ": " << std::get<0>(*this) << " " << std::get<1>(*this) << " " << std::get<2>(*this) << std::endl;
  }

  Userdata()
  {
  }

};


int main(int argc, char *argv[])
{
  Userdata<int> test;
  /*
  test.assign1("assign1", 1, "test1", 1);
  test.print();
  */
  test.assign2(2, "test2", 2);
  test.print("assign2");
  test.assign3(3, "test3", 3);
  test.print("assign3");
}

结果

assign2: 0  0 
assign3: 3 test3 3

assign3给出预期结果。 所以,虽然我可以轻松使用assign3函数,但我仍然想知道assign2有什么问题。

1 个答案:

答案 0 :(得分:2)

(std::tuple<idtype, WideString, int>)(*this)

创建一个然后分配给的新临时文件。转而参考:

(std::tuple<idtype, WideString, int>&)(*this)=std::make_tuple(id, name,  lvl);