21

我在 Curiously Recurring Template Pattern 上读过的所有材料似乎都是一层继承,即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.get().print() 和 b.get().print() 吗?

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

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

每个类在其构造函数中接受 6 个左右的参数,其中许多是可选的并且具有合理的默认值。为了避免可选参数的乏味,最好的解决方案是使用命名参数惯用语

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

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

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

以前有人过这个问题,解决方案似乎是某种奇怪的重复模板模式。我使用的特殊口味是here

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

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

4

3 回答 3

9

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

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<>],所以这样的事情可能是处理它的最不笨拙的方式。


从您的其他答案来看,(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<B> >或类似的东西,因为B还不存在。

于 2010-05-12T17:48:30.287 回答
4

这是我已经解决的问题,使用 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;
};
于 2010-05-12T17:42:04.730 回答
1

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

可能,您的任务最好使用类型擦除,而不是奇怪地重复出现的模板模式。可能,将是有用的

于 2010-05-12T18:17:39.450 回答