假设我有一个具有多个构造函数的不可复制类,如下所示
class Foo: boost::noncopyable
{
public:
Foo(std::string s) {...}; // construct one way
Foo(int i) {...}; // construct another way
}
现在,我想构造一个对象,并选择在运行时使用哪个构造函数:
我可以用这样的指针来做到这一点: -
boost::shared_ptr<Foo> f;
if (condition)
f.reset(new Foo(myString));
else
f.reset(new Foo(myInteger));
// common code follows
f->doSomethingComplicated(...);
但这感觉混乱而缓慢。有没有一种简单的方法来选择对象的构造函数而不诉诸动态分配?
更多细节:Foo
上面的类只是为了说明问题。实际涉及的类是 Windows Gdiplus::Bitmap
- http://msdn.microsoft.com/en-gb/library/windows/desktop/ms534420(v=vs.85)。 aspx