【问题标题】:How to write curiously recurring templates with more than 2 layers of inheritance?如何编写具有超过 2 层继承的奇怪重复模板?
【发布时间】:2011-02-18 17:52:49
【问题描述】:

我读过的关于奇怪循环模板模式的所有材料似乎都是一层继承,即BaseDerived : Base<Derived>。如果我想更进一步怎么办?

#include <iostream>
using std::cout;


template<typename LowestDerivedClass> class A {
public:
    LowestDerivedClass& get() { return *static_cast<LowestDerivedClass*>(this); }
    void print() { cout << "A\n"; }
};
template<typename LowestDerivedClass> class B : public A<LowestDerivedClass> {
    public: void print() { cout << "B\n"; }
};
class C : public B<C> {
    public: void print() { cout << "C\n"; }
};

int main()
{
    C c;
    c.get().print();

//  B b;             // Intentionally bad syntax, 
//  b.get().print(); // to demonstrate what I'm trying to accomplish

    return 0;
}

我怎样才能重写这段代码以编译不出错并显示

C

使用 c.get().print() 和 b.get().print() ?

动机:假设我有三个班级,

class GuiElement { /* ... */ };
class Window : public GuiElement { /* ... */ };
class AlertBox : public Window { /* ... */ };

每个类在其构造函数中接受 6 个左右的参数,其中许多是可选的并且具有合理的默认值。对于avoid the tedium of optional parameters,最好的solution是使用Named Parameter Idiom

这个习惯用法的一个基本问题是参数类的函数必须返回它们被调用的对象,但是一些参数被提供给 GuiElement,一些给 Window,还有一些给 AlertBox。你需要一种写法:

AlertBox box = AlertBoxOptions()
    .GuiElementParameter(1)
    .WindowParameter(2)
    .AlertBoxParameter(3)
    .create();

但这可能会失败,因为例如 GuiElementParameter(int) 可能返回 GuiElementOptions&,它没有 WindowParameter(int) 函数。

这之前是asked,解决方案似乎是某种奇怪重复的模板模式。我使用的特殊风味是here

不过,每次我创建一个新的 Gui 元素时都要编写很多代码。我一直在寻找简化它的方法。复杂性的一个主要原因是我使用 CRTP 来解决 Named-Parameter-Idiom 问题,但我有三层而不是两层(GuiElement、Window 和 AlertBox),而且我的 current workaround 使我的类数量增加了四倍有。 (!) 例如,Window、WindowOptions、WindowBuilderT 和 WindowBuilder。

这让我想到了我的问题,我本质上是在寻找一种更优雅的方式来在长继承链(例如 GuiElement、Window 和 Alertbox)上使用 CRTP。

【问题讨论】:

  • 您希望c.get().print() 输出“C\nB\n”还是希望您注释掉的行编译并提供“B\n”一半?
  • 后者。编辑了我的问题,希望更清楚。
  • 你应该说明你想要这个。因为它是唯一可能的答案是:不,你不能。
  • 我对命名参数习语的理解不同,你的所有这些方法都会返回AlertBox&amp;,如果他们碰巧在后台使用了其他对象/ctors,那就没关系了
  • Nope.. 如果我想创建一个 Window,或者从 Window 派生的另一个类怎么办。除非我想剪切和粘贴大量代码,否则相应的构建器将从他们的基础构建器继承,例如AlertBoxBuilder : public WindowBuilder。如果我在创建一个Window,WindowBuilder的命名参数方法需要返回WindowBuilder&。如果我正在创建一个 AlertBox,他们需要返回 AlertBox&。这是 CRTP 可以解决的问题。

标签: c++ templates crtp


【解决方案1】:

我并不完全清楚您希望完成什么,但这与您的要求非常接近。

template <typename LowestDerivedClass> class A {
public:
  LowestDerivedClass &get() {
    return *static_cast<LowestDerivedClass *>(this); 
  }
  void print() {
    cout << "A"; 
  }
};

template <typename LowestDerivedClass>
class Bbase : public A<LowestDerivedClass> {
public:
  void print() {
    cout << "B";
    this->A<LowestDerivedClass>::print();
  }
};

class B : public Bbase<B> {};

class C : public Bbase<C> {
public:
  void print() {
    cout << "C";
    this->Bbase<C>::print();
  }
};

int main() {
  C c;
  c.print();
  cout << endl;
  B b;
  b.print();
  cout << endl;
}

我更改了输出以更好地说明继承。在您的原始代码中,您不能假装 B 不是模板 [您希望最好的是 B&lt;&gt;],所以这样的事情可能是处理它的最不笨拙的方式。


从您的其他答案来看,(2)是不可能的。如果函数的参数足以推断它们,则可以省略函数的模板参数,但是对于类,您必须提供一些东西。 (1) 可以做,但是很别扭。撇开所有不同的层:

template<typename T> struct DefaultTag { typedef T type; };
template<typename Derived = void>
class B : public A<Derived> { /* what B should do when inherited from */ };
template<>
class B<void> : public A<DefaultTag<B<void> > > { /* what B should do otherwise */ };

你必须在每个级别上做类似的事情。就像我说的,尴尬。你不能简单地说typename Derived = DefaultTag&lt;B&gt; &gt; 或类似的东西,因为B 还不存在。

【讨论】:

  • “我不太清楚你希望完成什么”——在我的问题中添加了一个冗长的动机部分。
  • 我提出了一个非常相似的建议,但我也有一个 Cbase 类(与 AbaseBbase 的模式相同;C 派生自它而不是 Bbase。 AFAIK 的唯一优势是它允许您在不更改现有继承的情况下继续扩展模式。
【解决方案2】:

这是我已经解决的问题,使用 CRTP 的变体来解决我的动机示例中提出的问题。最好从底部开始阅读并向上滚动..

#include "boost/smart_ptr.hpp"
using namespace boost;

// *** First, the groundwork....
//     throw this code in a deep, dark place and never look at it again
//
//     (scroll down for usage example)

#define DefineBuilder(TYPE, BASE_TYPE) \
    template<typename TargetType, typename ReturnType> \
    class TemplatedBuilder<TYPE, TargetType, ReturnType> : public TemplatedBuilder<BASE_TYPE, TargetType, ReturnType> \
    { \
    protected: \
        TemplatedBuilder() {} \
    public: \
        Returns<ReturnType>::me; \
        Builds<TargetType>::options; \

template<typename TargetType>
class Builds
{
public:
    shared_ptr<TargetType> create() {
        shared_ptr<TargetType> target(new TargetType(options));
        return target;
    }

protected:
    Builds() {}
    typename TargetType::Options options;
};

template<typename ReturnType>
class Returns
{
protected:
    Returns() {}
    ReturnType& me() { return *static_cast<ReturnType*>(this); }
};

template<typename Tag, typename TargetType, typename ReturnType> class TemplatedBuilder;
template<typename TargetType> class Builder : public TemplatedBuilder<TargetType, TargetType, Builder<TargetType> > {};

struct InheritsNothing {};
template<typename TargetType, typename ReturnType>
class TemplatedBuilder<InheritsNothing, TargetType, ReturnType> : public Builds<TargetType>, public Returns<ReturnType>
{
protected:
    TemplatedBuilder() {}
};

// *** preparation for multiple layer CRTP example *** //
//     (keep scrolling...)

class A            
{ 
public: 
    struct Options { int a1; char a2; }; 

protected:
    A(Options& o) : a1(o.a1), a2(o.a2) {}
    friend class Builds<A>;

    int a1; char a2; 
};

class B : public A 
{ 
public: 
    struct Options : public A::Options { int b1; char b2; }; 

protected:
    B(Options& o) : A(o), b1(o.b1), b2(o.b2) {}
    friend class Builds<B>;

    int b1; char b2; 
};

class C : public B 
{ 

public: 
    struct Options : public B::Options { int c1; char c2; };

private:
    C(Options& o) : B(o), c1(o.c1), c2(o.c2) {}
    friend class Builds<C>;

    int c1; char c2; 
};


// *** many layer CRTP example *** //

DefineBuilder(A, InheritsNothing)
    ReturnType& a1(int i) { options.a1 = i; return me(); }
    ReturnType& a2(char c) { options.a2 = c; return me(); }
};

DefineBuilder(B, A)
    ReturnType& b1(int i) { options.b1 = i; return me(); }
    ReturnType& b2(char c) { options.b2 = c; return me(); }
};

DefineBuilder(C, B)
    ReturnType& c1(int i) { options.c1 = i; return me(); }
    ReturnType& c2(char c) { options.c2 = c; return me(); }
};

// note that I could go on forever like this, 
// i.e. with DefineBuilder(D, C), and so on.
//
// ReturnType will always be the first parameter passed to DefineBuilder.
// ie, in 'DefineBuilder(C, B)', ReturnType will be C.

// *** and finally, using many layer CRTP builders to construct objects ***/

int main()
{
    shared_ptr<A> a = Builder<A>().a1(1).a2('x').create();
    shared_ptr<B> b = Builder<B>().a1(1).b1(2).a2('x').b2('y').create();
    shared_ptr<B> c = Builder<C>().c2('z').a1(1).b1(2).a2('x').c1(3).b2('y').create(); 
    // (note: any order works)

    return 0;
};

【讨论】:

    【解决方案3】:

    我认为实现一些通用机制是不可能的。每次继承基类时,您都必须明确指定确切的模板参数,无论之间放置了多少间接级别(根据您的回答判断:现在有 2 个级别:您不将 C 直接传递给基类,但是C包裹在标签结构中,看起来像一条咬自己尾巴的蛇)

    对于您的任务,使用类型擦除可能会更好,而不是奇怪地重复出现的模板模式。可能,this 会很有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      相关资源
      最近更新 更多