Mic*_*LoL 6 c++ type-traits visual-c++ c++17
我正在使用这个成员函数来获取指向对象的指针:
virtual Object* Create()
{
return new Object();
}
Run Code Online (Sandbox Code Playgroud)
它是虚拟的,所以我可以得到指向派生对象的指针,现在我这样做:
virtual Object* Create()
{
return new Foo();
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但我想做这样的事情以防止任何错误并使其更容易,这样我就不必每次创建新类时都重写该函数:
virtual Object* Create()
{
return new this();
}
Run Code Online (Sandbox Code Playgroud)
我试图找到如何做到这一点,但找不到任何有用的东西,也许这是不可能的。我在 C++17 中使用 MSVC 编译器
son*_*yao 10
您可以从this指针获取类型为
virtual Object* Create() override
{
return new std::remove_pointer_t<decltype(this)>;
}
Run Code Online (Sandbox Code Playgroud)
PS:注意还是需要在每个派生类中重写成员函数。根据您的需求,您可以使用CRTPCreate在基类中实现。例如
template <typename Derived>
struct Object {
Object* Create()
{
return new Derived;
}
virtual ~Object() {}
};
Run Code Online (Sandbox Code Playgroud)
然后
struct Foo : Object<Foo> {};
struct Bar : Object<Bar> {};
Run Code Online (Sandbox Code Playgroud)