How to secure CRTP against providing wrong superclass? [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-02 02:29:08

问题


In the curiously recurring template pattern, we write

template <class Derived>
class Base {
};

class Derived : public Base<Derived> {
};

What would be a good way to make the code robust another copy-paste omissions, so that the following snippet throws a compile-time error:

class AnotherDerived : public Base<Derived> {
};

I'm using Visual C++ 2013.


回答1:


Make Base's destructor private, and then make Derived a friend of Base<Derived>:

template <class Derived>
class Base {
    private: ~Base() = default;
    friend Derived;
};

class Derived : public Base<Derived> {
};

This does not actually make doing

class AnotherDerived : public Base<Derived> {
};

illegal, but any attempt to actually construct an AnotherDerived will fail.




回答2:


You can static_assert that the argument derives from Base<Argument>, but that's as far as you can go.



来源:https://stackoverflow.com/questions/28548958/how-to-secure-crtp-against-providing-wrong-superclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!