c++ - 仅为派生类启用模板化基类

标签 c++ templates inheritance reflection typedef

我将如何着手做以下等同​​的事情?

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()

最佳答案

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

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

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

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

关于c++ - 仅为派生类启用模板化基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68969652/

相关文章:

c++ - 如何解决 WSAEWOULDBLOCK 错误

c++ - 根据参数个数调用模板中的函数

php - Silex v1.3 到 Silex v2 : Twig_Error_Runtime

c++ - "Extra Qualification on Member"模板类错误

C++通过继承在具有 protected 构造函数的基类堆上分配对象

c# - 在基静态类中获取继承的调用者类型名称

c++ - 错误 C4430 : missing type specifier - int assumed

c++ - 同时将多个十六进制数附加到 QByteArray

c++ - 指向函数编译错误的指针

c++ - ctor和dtor从抽象基类通过其他抽象类继承到具体