我试图为从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有什么问题。
发布于 2017-08-16 02:11:29
(std::tuple<idtype, WideString, int>)(*this)创建一个新的临时对象,然后分配给它。改为参考:
(std::tuple<idtype, WideString, int>&)(*this)=std::make_tuple(id, name, lvl);https://stackoverflow.com/questions/45703963
复制相似问题