【问题标题】:How to pass data to reference wrapper如何将数据传递给引用包装器
【发布时间】:2019-01-08 21:34:56
【问题描述】:

考虑以下代码:

//option no 1
struct foo{
    foo(baz &b) : _b(b){}

    std::reference_wrapper<baz> _b;
};

//option no 2
struct bar{
    bar(std::reference_wrapper<baz> b) : _b(b){}

    std::reference_wrapper<baz> _b;
};

我想知道初始化foobar 之间是否有任何实际区别。如果是这样,每种解决方案的优缺点是什么,应该首选哪个?

【问题讨论】:

    标签: c++ c++11 reference reference-wrapper


    【解决方案1】:

    转换运算符的类型至少有区别:

    struct tobaz
    {
        operator baz&() const { static baz b; return b; }
    };
    

    然后

    foo{tobaz()}; // Compile
    bar{tobaz()}; // Won't compile
    

    因为只能发生一次用户转化。

    Demo

    operator std::reference_wrapper&lt;baz&gt;() 的结构的另一端会发生错误。

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 2011-02-22
      • 2017-06-05
      • 2013-04-24
      • 2019-09-22
      • 2017-07-13
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多