【问题标题】:Copying a std::tuple复制 std::tuple
【发布时间】:2017-08-16 01:55:07
【问题描述】:

我试图将一些值分配给从 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 有什么问题。

【问题讨论】:

  • 顺便说一句,你确定要在这里继承,而不是简单的组合吗?
  • @BaummitAugen 我打算提出相同的建议,但我想也许有一些我没有掌握的东西。
  • @BaummitAugen 感谢以下回复。是的,我想要继承,因为其他函数希望在那里与元组交互,所以这似乎是最简单的路径。 :)

标签: c++ stdtuple


【解决方案1】:
(std::tuple<idtype, WideString, int>)(*this)

创建一个新的临时对象,然后分配给它。改为引用:

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

【讨论】:

    猜你喜欢
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    相关资源
    最近更新 更多