【问题标题】:enable templated base class only for derived classes仅为派生类启用模板化基类
【发布时间】:2021-10-28 08:27:13
【问题描述】:

我将如何执行以下等效操作?

template < class T, typename = std::enable_if< std::is_base_of< Self, T >::value > > // Can not use std::is_base_of on self
class Self {
protected:
    typedef T self;
};

class ValidDerived : public Self< ValidDerived > { }; // This should compile because T is itself

class InvalidDerived : public Self< ValidDerived > { }; // This should not compile because T is not itself

我正在尝试实现反射,为此我必须采取的步骤之一是获取最派生类的typeid( self ).name()

【问题讨论】:

  • AFAIK 你将无法做到这一点。派生类型在 CRTP 基类的上下文中将是不完整的——因此您将无法检查 T 是否与 Self&lt;T&gt; 相关

标签: c++ templates inheritance reflection typedef


【解决方案1】:

在 CRTP 中,Tclass MyClass : Self&lt;MyClass&gt; {}; 中不完整。

您可以在应该调用/实例化的方法中添加额外的检查(例如构造函数/析构函数):

template<class T>
class Self
{
protected:
    using self = T;

    Self() { static_assert(std::is_base_of<Self, T >::value); }
};

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2018-12-14
    • 2017-06-12
    • 2016-08-17
    相关资源
    最近更新 更多