首页 > 解决方案 > 仅为派生类启用模板化基类

问题描述

我将如何去做相当于以下的事情?

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()最派生类。

标签: c++templatesinheritancereflectiontypedef

解决方案


在 CRTP 中,Tclass MyClass : Self<MyClass> {};.

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

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

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

推荐阅读