gpt4 book ai didi

c++ - 复制 std::tuple

转载 作者:行者123 更新时间:2023-11-30 03:29:25 27 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于c++ - 复制 std::tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com