CRTP-我可以使用私人方法吗?

时间:2019-05-26 14:15:02

标签: c++ crtp static-polymorphism

我正在实现静态多态性:

template<typename T>
class Base {
public:
    void method() {
         // do something
         impl();
         // do something else
    }
    void impl() { // intended to be private
        static_cast<T*>(this)->impl();
    }
};

class Derived : public Base<Derived> {
public:
     void impl() { // intended to be private
     }
};

这段代码是动态多态类的静态实现,其中void impl()是虚拟的和私有的。

我已经实现了多态性(静态)。但是我必须将方法void impl()公开,以允许从基类对其进行访问。我希望方法void impl()再次私有。能做到吗?

更新: 我不想写

friend class Base<Derived>;

在Derived类中,因为它允许Base访问Derived的所有成员。

1 个答案:

答案 0 :(得分:3)

在您的Derived类中添加一行:

class Derived : public Base<Derived> {
public:
private:
     void impl() { // intended to be private
     }
     friend class Base<Derived>;
};

它将基类指定为朋友,允许我以impl为私有的方式编译代码。

编辑

如@Oliv的评论中所建议,“律师-客户”习语的实现如下所示:


template<typename T>
class Attorney;

template<typename T>
class Base {
public:
    void method() {
        // do something
        impl();
        // do something else
    }
private:
    void impl() { // intended to be private
        Attorney<T>::impl(*static_cast<T*>(this));
    }
};


class Derived : public Base<Derived> {
private:
    void impl() { // intended to be private
    }
    friend class Attorney<Derived>;
};

template<typename T>
class Attorney {
private:
    friend class Base<Derived>;

    static void impl(Derived & c) { // add additional parameters as needed by impl
        c.impl();
    }
};