0

メンバーを保持するホスト クラスがあるとします。

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;}
};
4

1 に答える 1

1

ポリシーをホストから継承せずに CRTP を実行する方法を次に示します。

template <typename DerivedT>
struct p1
{
    DerivedT&       derived()       { return *static_cast<DerivedT*>(this);       }
    const DerivedT& derived() const { return *static_cast<const DerivedT*>(this); }

    void f1()
    {
        derived().member += 1;
    }
};

template <typename DerivedT>
struct p2
{
    DerivedT&       derived()       { return *static_cast<DerivedT*>(this);       }
    const DerivedT& derived() const { return *static_cast<const DerivedT*>(this); }

    void f2()
    {
        derived().member *= 2;
    }
};

struct host : public p1<host>, public p2<host>
{
     double member;
};
于 2013-09-12T06:46:19.960 に答える