我希望能够添加到对象中的一些不同类型的数据(此处称为&#34; A&#34;和#34; B&#34;)。如果我以相同的顺序为两个不同的对象添加它们,将一个复制到另一个可以正常工作(例如A<B<Point> > abPoint1; A<B<Point> > abPoint2 = abPoint1;
)。但是,如果我以不同的顺序添加它们(例如A<B<Point> > abPoint; B<A<Point> > baPoint = abPoint; // compiler error
),因为类型签名不相同。如果没有明确处理指数数量的mixin组合,有没有办法做到这一点?
这是一个用于测试的MWE:
// Standard point representation
struct Point
{
double x,y,z;
};
// A mixin to add an 'A' value to a point
template<class Base>
class A : public Base
{
public:
double a;
};
// A mixin to add an 'B' value to a point
template<class Base>
class B : public Base
{
public:
double b;
};
int main()
{
A<Point> aPoint;
B<Point> bPoint;
// A<Point> a2Point = bPoint; // obviously we can't do this
A<B<Point> > abPoint;
B<A<Point> > baPoint;
abPoint = baPoint; // Something like this seems like it should be possible
return 0;
}
更好的是,有没有办法只复制&#34;可用&#34;这些数据?那就是:
A<B<C<D<Point>>>> abcdPoint;
A<C<Point>> acPoint;
abcdPoint = acPoint;
只会复制A和C中的成员。
答案 0 :(得分:0)
为了能够展示我认为没有真正测试的答案,看看它是否有效,我会称之为答案。
template<class BASE>
class A {
public:
A<BASE> operator=(const &A<BASE> right) {
// does not block all errors, but catches some:
static_assert( std::is_base_of< A, BASE >::value, "CRTP failure" );
auto* dis = static_cast<BASE*>(this);
BASE::operator=(right);
dis->a = right.a;
return this;
}
double a;
};
template<class BASE>
class B {
public:
B<BASE> operator=(const &B<BASE> right) {
// does not block all errors, but catches some:
static_assert( std::is_base_of< B, BASE >::value, "CRTP failure" );
auto* dis = static_cast<BASE*>(this);
dis->b = right.b;
BASE::operator=(right);
return this;
}
double b;
};
class aPoint: public A<aPoint>, Point {};
class bPoint: public B<bPoint>, Point {};
class abPoint: public B < A<abPoint> > {};
class baPoint: public A < B<baPoint> > {};
答案 1 :(得分:0)
我尽我所能充实你的榜样。将abPoint复制到baPoint可以正常工作。
#include <iostream>
struct Point
{
public:
double x,y,z;
};
// A mixin to add an 'A' value to a point
template<class Base>
class A : public Base
{
public:
A& operator=( const Point& rhs )
{
Point::operator=(rhs);
return *this;
}
template <typename T_RHS>
A& operator=( const T_RHS& rhs )
{
Base::operator=(rhs);
a = rhs.a;
return *this;
}
double a;
};
// A mixin to add an 'B' value to a point
template<class Base>
class B : public Base
{
public:
B& operator=( const Point& rhs )
{
Point::operator=(rhs);
return *this;
}
template <typename T_RHS>
B& operator=( const T_RHS& rhs )
{
Base::operator=(rhs);
b = rhs.b;
return *this;
}
double b;
};
int main()
{
Point point;
A<Point> aPoint;
aPoint = point;
B<Point> bPoint;
bPoint = point;
B< A<Point> > baPoint;
A< B<Point> > abPoint;
abPoint = baPoint;
// Fails
//aPoint = bPoint;
//bPoint = aPoint;
// This works
aPoint.Point::operator=(bPoint);
bPoint.Point::operator=(aPoint);
return 0;
}