C++ 复制std::tuple
我试图给从std::tuple派生的类分配一些值。 我想到的第一件事是使用C++ 复制std::tuple,c++,stdtuple,C++,Stdtuple,我试图给从std::tuple派生的类分配一些值。 我想到的第一件事是使用生成元组,然后用操作符=复制它,但这不起作用 如果我手动分配元组的单个值,那么就没有问题了 所以我写了一段代码,从项目中提取出来,专门测试这一点: #include <tuple> template <class idtype> class Userdata: public std::tuple<idtype, WideString, int> { public: /* comp
生成元组,然后用操作符=
复制它,但这不起作用
如果我手动分配元组的单个值,那么就没有问题了
所以我写了一段代码,从项目中提取出来,专门测试这一点:
#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");
}
只有assign3
给出预期结果。
因此,虽然我可以很容易地使用assign3
函数,但我仍然想知道assign2
(std::tuple)(*这个)
(std::tuple<idtype, WideString, int>)(*this)
创建一个新的临时文件,然后将其指定给。转换为引用:
(std::tuple<idtype, WideString, int>&)(*this)=std::make_tuple(id, name, lvl);
(std::tuple&)(*this)=std::make_tuple(id、name、lvl);
Btw,你确定你想在这里继承而不是简单的组合吗?@BaummitAugen我也打算提出同样的建议,但我想可能有些东西我没有领会。@BaummitAugen感谢下面的回复。是的,我想要继承,因为其他函数希望在那里与元组交互,所以这似乎是最容易遵循的路径。:)
(std::tuple<idtype, WideString, int>&)(*this)=std::make_tuple(id, name, lvl);