在几乎相同的结构之间传递成员值
问题描述:
我不知道是否有人解决了以下问题,我有两个几乎相同的结构,我需要将结构A中的值传递给结构B,并且它们有一个成员的差异。在几乎相同的结构之间传递成员值
例子看起来是这样的,我有以下结构:
struct insideA
{
double C1;
double C2;
int C3;
str C4;
};
struct insideB
{
int D3;
str D4;
};
struct A
{
insideA inA;
double c;
std::string d;
} a;
struct B
{
insideB inB;
double c;
std::string d;
} b;
既然结构A和B都几乎相似,但并不完全相同,如果我们想象的B填充,我可以很容易地通过会员从动地重视成员:
a.inA.C3 = b.inB.D3;
a.inA.C4 = b.inB.D4;
a.c = b.c;
a.d = b.d;
而且现在有所有b的,我可以填充的其他成员的信息。所以我的问题是,我必须用不同的结构执行大约30或40次,只有结构的第一个成员发生变化,那么是否有更好的方法来完成此工作,而不是将值的struct成员传递给struct成员b单独吗?
答
让我们使用模板!
template <struct Inside>
struct AorB
{
Inside in;
double c;
std::string d;
template <struct OtherInside>
AorB& operator=(const AorB<OtherInside>& that) {
in = that.in;
c = that.c;
d = that.d;
}
};
struct A : AorB<insideA>
{
template <struct OtherInside>
A& operator=(const AorB<OtherInside>& that) {
AorB<insideA>::operator=(that);
return *this;
}
};
struct B : AorB<insideB>
{
template <struct OtherInside>
B& operator=(const AorB<OtherInside>& that) {
AorB<insideB>::operator=(that);
return *this;
}
};
您可以将此想法扩展到内部类。
+0
嘿, 感谢您的快速回复,我试图仔细描述我的问题,但我忘了澄清我必须通过的所有不同的结构之间,他们每个人的“身体”成员是不同的,所以用这种方法,我需要确实需要为他们每个人做一个类似的解决方案,然后看看使用哪个模板在这种情况下,我想如果有办法以某种方式实现自动化 – Pedro
使一个基类包含相同的成员并实现复制。 “几乎相同”不会帮你太多 – user463035818
你可以修改现有的结构定义吗? – nate
不,我不能编辑现有的结构,因为它是在驱动程序中,我无法访问源代码:( – Pedro