CRTP - 保持实施隐藏在公众面前

时间:2016-10-10 19:52:35

标签: c++ crtp

我使用Curiously Recurring Template Pattern创建具有通用接口但具体实现的类。

我在网络上找到的大多数CRTP示例都使用struct,因此使用它们的代码可以直接调用implementation()而不是interface()

有人建议将implementation()放入Derived的私有部分并添加friend Base。然而,这似乎在某种程度上是不优雅的。

我试图找到一个解决方案,让implementation()隐藏在公众面前。这是解决方案,它使用Proxy内的内部Base类。

template<class T> class Base
{
public:
    void interface()
    {
        return static_cast<Proxy*>(this)->implementation();
    }

private:
    class Proxy: public T
    {
        // friend Base; /* uncomment to allow full access */
        friend void Base::interface();
    };
};

class Derived: public Base<Derived>
{
protected:
    void implementation()
    {

    }
};

现在使用Derived的代码将被强制拨打interface(),因为implementation()受到保护。

我想在这里讨论解决方案的可能问题。

0 个答案:

没有答案
相关问题