我试图将一些值赋给从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
有什么问题。
答案 0 :(得分:2)
(std::tuple<idtype, WideString, int>)(*this)
创建一个然后分配给的新临时文件。转而参考:
(std::tuple<idtype, WideString, int>&)(*this)=std::make_tuple(id, name, lvl);