bartop
bartop

Reputation: 10315

How to pass data to reference wrapper

Consider following piece of code:

//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;
};

I am wondering if there are any practical differences between initializing foo and bar. If so, what are the pros and cons of each solution and which should be preferred?

Upvotes: 0

Views: 71

Answers (1)

Jarod42
Jarod42

Reputation: 217593

There are at least difference with types with conversion operator:

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

Then

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

As only one user conversion can take place.

Demo

Error would happen the other side for struct with operator std::reference_wrapper<baz>().

Upvotes: 1

Related Questions