我正在使用这个成员函数来获取指向对象的指针:
virtual Object* Create()
{
return new Object();
}
它是虚拟的,所以我可以获得指向派生对象的指针,现在我这样做:
virtual Object* Create()
{
return new Foo();
}
它工作正常,但我想做这样的事情来防止任何错误并使其更容易,这样我就不必每次创建新类时都重写该函数:
virtual Object* Create()
{
return new this();
}
我试图找到如何做到这一点,但找不到任何有用的东西,也许这是不可能的。我正在使用带有 C++17 的 MSVC 编译器
您可以从以下位置获取类型this
指针为
virtual Object* Create() override
{
return new std::remove_pointer_t<decltype(this)>;
}
LIVE https://wandbox.org/permlink/rYeSQbbHHDcycWJo
PS:请注意,您仍然需要重写每个派生类中的成员函数。根据您的需求,与CRTP https://en.cppreference.com/w/cpp/language/crtp你可以实施Create
在基类中。例如。
template <typename Derived>
struct Object {
Object* Create()
{
return new Derived;
}
virtual ~Object() {}
};
then
struct Foo : Object<Foo> {};
struct Bar : Object<Bar> {};
LIVE https://wandbox.org/permlink/jG8rrKLrOnGCWFMX
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)