在两个构造函数之间进行选择 [英] Selecting between two constructors

查看:126
本文介绍了在两个构造函数之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我有一个具有两个构造函数的不可复制对象。我需要创建一个对象与一个构造函数,然后在一些常见的代码中使用它: -

Problem: I have a non-copyable object with two constructors. I need to create an object with one of the constructors and then use it within some common code:-

对于可复制对象,它将看起来像这样,

With a copyable object it would look like this, and be easy:

Object a;

if (condition) 
   a = Object(p1);
else
   a = Object(p2,p3,p4);

a.doSomething();

但是,对象是不可复制的,所以我不得不这样做:

But, the object is non-copyable, so I've had to do this:

boost::scoped_ptr<Object> a;

if (condition) 
   a = new Object(p1);
else
   a = new Object(p2,p3,p4);

a->doSomething();

这太麻烦了。有没有更好的解决方案?

This feels too complex. Is there a better solutiuon?

推荐答案

这是一个非常可怕的黑客,假设 Object 是默认可构造的:

Here's a very terrible hack, assuming Object is default-constructible:

Object a;
a.~Object();

if (condition) { ::new (&a) Object(p1); }
else           { ::new (&a) Object(p2, p3, p4); }

不要使用这个。

Don't use this.

另一个选项是使用联合,但是你需要在该设置中手动调用析构函数。

Another option is using a union, but you'll need to invoke the destructor manually in that setup as well.

一个更清洁的解决方案可以通过 Boost.Optional (使用就地工厂)。 (感谢@ K-Ballo挖掘细节!)

A cleaner solution could be achieved with Boost.Optional (using in-place factories). (Thanks to @K-Ballo for digging up the details!)

#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>

struct Object
{
    explicit Object(int) {}
    explicit Object(int, float, std::string) {}

    Object(Object const &)             = delete;
    Object(Object &&)                  = delete;
    Object & operator=(Object const &) = delete;
    Object & operator=(Object &&)      = delete;
};

boost::optional<Object> a;

if (condition) { a = boost::in_place(0); }
else           { a = boost::in_place(0, 1.0f, "two" ); }

这篇关于在两个构造函数之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆