C++ 如何在策略之间共享成员?

C++ 如何在策略之间共享成员?,c++,inheritance,static-polymorphism,policy-based-design,C++,Inheritance,Static Polymorphism,Policy Based Design,假设我有一个宿主类,其中包含一个成员: template<class p1, class p2> struct host : public p1, public p2 { double member; }; 有办法吗 我能想到的一种方法是通过虚拟继承从另一个包含成员的类派生p1和p2,这使事情变得复杂 另一种方法是将成员作为函数的参数传递给策略。大概是这样的: template<class p1, class p2> struct host : public p1,

假设我有一个宿主类,其中包含一个成员:

template<class p1, class p2>
struct host : public p1, public p2 {
 double member;
};
有办法吗

我能想到的一种方法是通过虚拟继承从另一个包含成员的类派生
p1
p2
,这使事情变得复杂

另一种方法是将成员作为函数的参数传递给策略。大概是这样的:

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

这里有一种在不从主机继承策略的情况下执行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;
};
模板
结构p1
{
DerivedT&derived(){return*static_cast(this);}
const DerivedT&derived()const{return*static_cast(this);}
void f1()
{
派生().成员+=1;
}
};
模板
结构p2
{
DerivedT&derived(){return*static_cast(this);}
const DerivedT&derived()const{return*static_cast(this);}
无效f2()
{
派生().成员*=2;
}
};
结构主机:公共p1,公共p2
{
双重成员;
};

为什么CRTP不可能?做你想做的事是你工作的全部目的CRTP@CortAmmon据我所知,这是因为当策略从模板化主机继承时,主机需要有一个完整的类型。我将用update(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;}
};
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;
};