用于转发协变返回的 C++ 抽象基础模板

标签 c++ crtp

我正在尝试使用 CRTP 和协方差来实现转发:

class Display {  // interface
    virtual Display& drawCircle(...) = 0;
    virtual Display& drawRect(...) = 0;
    // etc. lots of these.
};
class ADisplay<R> : public Display {
     virtual Display& getWrapped();
     virtual R& drawCircle(...) { getWrapped().drawCircle(...); return *this; }
     virtual R& drawRect(...) { getWrapped().drawRect(...); return *this; }
     // etc?
};
class B : public ADisplay<B> {
     Display& wrapped;
     virtual Display& getWrapped() { return wrapped; }
     B& methodSpecificToB() {...}
};

这将以“构建器”样式使用:

B b;
b.drawCircle(1,2,3)
 .drawRect(4,5,6)
 .methodSpecificToB();

这也许不足为奇,因为 ADisplaynot completely defined 不起作用。在实例化时。

你能想出其他方法吗?

最佳答案

就像一个提示(我现在不想详细说明,在我这边已经晚了),你总是可以这样做(注意而没有抽象的Display接口(interface)):

template<class R>
class ADisplay<R> 
{
public:
    R& drawCircle(...) 
    { 
        static_cast<R*>(this)->drawCircleImpl(...); 
        return *static_cast<R*>(this); 
    }
    R& drawRect(...) 
    { 
        static_cast<R*>(this)->drawRectImpl(...); 
        return *static_cast<R*>(this); 
    }
protected:
    R& drawCircleImpl(...)
    {
        // May be have some static assert here, if you want to have this method
        // 'abstract'. Otherwise provide some reasonable base implementation, or
        // delegate to a mixin (provided as another template parameter)
    }

    R& drawRectImpl(...)
    {  
        // Same as above ...
    }
};

抽象接口(interface)的目的是什么,客户端无论如何都必须知 Prop 体的实现方法?

关于用于转发协变返回的 C++ 抽象基础模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678915/

相关文章:

c++ - GCC,CMake,预编译头和维护依赖项

c++ - "Unresolved overloaded function type"尝试将 for_each 与 C++ 中的迭代器和函数一起使用时

c++ - 更新对象的属性时遇到问题?

c++ - CRTP子类和实例列表

C#——侵入式树结构,使用CRTP

c++ - 保护 CRTP 模式免受 "pure virtual"调用中的堆栈溢出

c++ - 如何对 unique_ptr 的 vector 进行排序?

c++ - VS 2010 中首选的多线程方法/库?

c++ - 来自 CRTP 基础的 Operator++ 对编译器不可见

c++ - 派生模板类对象的实例化