#include <memory>
class Base
{
std::shared_ptr<Base> create() const; // Returns a default constructed object
}
假设,从 Base
派生到任何程度的所有成员都是可复制构造和默认构造的。我想要的是
std::shared_ptr<Base> create() const;
创建适当动态类型的对象的方法,但我不想使用样板代码。
可以吗
std::shared_ptr<Base> create() const;
静态绑定(bind),但在内部以某种方式找到正确的类型并使用默认构造函数创建对象?可能使用 C++11。
最佳答案
create()
函数可能应该是静态的,因为您还没有实例。但如果没有参数,你就无法做你想做的事......当然,除非你使用模板:
class Base
{
public:
template<typename T>
static std::shared_ptr<Base> create() const
{
return std::shared<Base>(new T);
}
};
然后这样使用它:
std::shared_ptr<Base> ptr(Base::create<Foo>());
或者,如果您愿意的话:
std::shared_ptr<Base> ptr(Foo::create<Foo>());
关于c++ - 是否可以制作非虚拟创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11585232/