说我有一堂课:
class Foo{
public:
Foo(){
}
//Is it possible to create a function like this:
virtual Foo* createOb(){
//Should create a new Foo,Bar or Fiz, depending on the actual object type.
}
}
class Bar: public Foo{
public:
Bar(){
}
}
class Fiz: public Foo{
public:
Fiz(){
}
}
createOb()
在基类中是否可能有一个方法,因此在派生类之一的实例上调用createOb()时,就创建了派生类的实例?
是的,可以使用CRTP来完成。
首先,返回从中获取的原始指针new
是非常危险的。在c++
原始指针中,仅当它们不具有指向对象的所有权时才应使用。所以我自由使用unique_ptr
:
struct Base {
virtual auto create_obj() -> std::unique_ptr<Base>
{
return std::unique_ptr<Base>{};
}
};
// abstract works too:
struct Base {
virtual auto create_obj() -> std::unique_ptr<Base> = 0;
};
template <class Derived>
struct Base_crtp : Base {
auto create_obj() -> std::unique_ptr<Base> override /* final */
{
return std::unique_ptr<Base>{new Derived{}};
}
};
struct D1 : Base_crtp<D1>
{
};
struct D2 : Base_crtp<D2>
{
};
接着:
auto b1 = std::unique_ptr<Base>{new D1{}};
auto b2 = std::unique_ptr<Base>{new D2{}};
auto new_d1 = b1->create_obj();
auto new_d2 = b2->create_obj();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句