如何确保CRTP提供错误的超类? [英] How to secure CRTP against providing wrong superclass?

查看:149
本文介绍了如何确保CRTP提供错误的超类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好奇的重复模板模式中,我们写入

template <class Derived>
class Base {
};

class Derived : public Base<Derived> {
};

这将是一个很好的方法,使代码健壮另一个复制粘贴遗漏, snippet抛出编译时错误:

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> {
};

我使用Visual C ++ 2013。

I'm using Visual C++ 2013.

推荐答案

使基础的析构函数私有,然后使派生 的朋友

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> {
};

这实际上不会做

class AnotherDerived : public Base<Derived> {
};

非法,但任何尝试实际构造 AnotherDerived 将失败。

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

这篇关于如何确保CRTP提供错误的超类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆