メンバーを保持するホスト クラスがあるとします。
template<class p1, class p2>
struct host : public p1, public p2 {
double member;
};
そして、p1 と p2 で同じメンバーを使用したい:
struct p1 {
void f1() { host::member+=1;} // this is incorrect but I'm looking for this behavior
};
struct p2 {
void f2() {host::member*=2;}
};
それを行う方法はありますか?
私が考えることができる 1 つの方法は、仮想継承を介してメンバーを含む別のクラスから派生p1
するp2
ことです。これにより、物事が複雑になります。
もう 1 つは、メンバーを関数の引数としてポリシーに渡すことです。このようなもの:
template<class p1, class p2>
struct host : public p1, public p2 {
double member;
void hf1() { p1::f1(member);}
void hf2() { p2::f2(member);}
};
struct p1 {
void f1(double m) { m+=1;} // this is incorrect but I'm looking for this behavior
};
struct p2 {
void f2(double m) {m*=2;}
};
もう 1 つの考えは、CRTP を使用して、ポリシーからホストを取得し、ホストからポリシーを取得して、メンバーにアクセスできるようにすることusing
でしたが、それは不可能です。
更新 (1)
CRTPでの私の試み
template<class p1, class p2>
struct host : public p1, public p2 {
double member;
};
template<host_type>
struct p1 : public host_type { // error: invalid use of incomplete type 'struct host<p1,p2>'
void f1() { host_type::member+=1;}
};
template<host_type>
struct p2 : public host_type<p1,p2> { // error: expected template-name before '<' token
void f2() {host_type::member*=2;}
};