boost::in_place 将参数作为常量引用

boost::in_place taking arguments as const refs

本文关键字:引用 参数 常量 in place boost      更新时间:2023-10-16

我有一个类,构造函数将参数作为引用。例如。

class A
{
    A(Tracer& t) : m_t(t) { }
  private:
     Tracer& m_t;
};

我将这个class A作为 boost::可选,并且只想在需要时构建它。如果我使用 boost::in_place 来构建它。由于boost::in_place将参数作为const_refs,因此我不得不将构造函数的签名修改为

A(const Tracer& t) : m_t(const_cast<Tracer&>(t)  { }

还有其他方法可以通过引用传递对象吗?

软件限制是 boost 1.4.3,VS2010。

编辑:该类也不是可复制构造和可分配的。我没有在上面提到的示例类中展示这一点。

像这样:

#include <boost/optional.hpp>
#include <boost/ref.hpp>
struct Tracer
{
    Tracer() = default;
    Tracer(const Tracer&) = delete;
    Tracer(Tracer&&) = delete;
    Tracer& operator=(const Tracer&) = delete;
    Tracer& operator=(Tracer&&) = delete;
};
class A
{
public: // Note: I had to add this.
    A(Tracer& t) : m_t(t) { }
private:
     Tracer& m_t;
};
int main()
{
    Tracer tracer;
    boost::optional<A> x;
    x = boost::in_place(boost::ref(tracer));
}

boost::ref返回一个boost::reference_wrapper,将引用建模为值。