我将如何着手做以下等同的事情?
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 中,T
在 class 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/