boost::in_place 将参数作为常量引用
boost::in_place taking arguments as const refs
我有一个类,构造函数将参数作为引用。例如。
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
,将引用建模为值。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 具有常量引用参数的函数模板专用化
- C++:常量引用参数
- 字符串引用参数的效率C++
- 通过非常量引用参数修改常量引用参数
- 如何将指针变量作为引用参数传递?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 移动类的成员作为常量引用参数传递
- C++带有适用于左值和右值的引用参数的函数
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 委托构造函数和引用参数
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 如何强制函数仅接受左值引用参数
- 模板引用参数推断失败C++
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 将unique_ptr作为引用参数或常量传递unique_ptr引用