复制std :: tuple
问题描述:
我试图将一些值分配给派生自std :: tuple的类。 我想到的第一件事就是使用make_tuple
,然后将它复制到operator=
,但那不起作用。复制std :: tuple
如果我手动指定元组的单个值,则没有问题。从项目
所以我写了一小段代码,萃取,专门测试这个单一的东西:
#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);
顺便说一句,你确定你想在这里继承,而不是简单的组成? –
@BaummitAugen我打算提出相同的建议,但是也许有些事情我没有把握。 –
@BaummitAugen感谢下面的回复。是的,我想要继承,因为其他函数希望与那里的元组进行交互,所以它似乎是最容易遵循的路径。 :) – DrHell