1
union A {
    public:
    B b;
    inline operator B() const {
        return b;
    }
}
void doSomething(B& b){};
A a;
doSomething(a);

Getting "no matching function for call to" error using code similar to above. Can you not implicilty cast to reference like this?

Work around?

Thomas
  • 6,032
  • 6
  • 41
  • 79

2 Answers2

3

In the call doSomething(a), a is converted to an rvalue of type B using the conversion operator (which returns by value, hence the new temporary object).

Since rvalues can only be used as non-const reference or value parameters, you can't call doSomething with an rvalue.

Either declare doSomething to take its argument by const reference, by value, or by rvalue-reference. You could also make operator B return a reference to the b member if that's appropriate.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

The cast-operator returns b by value, and using that result when calling the doSomething function would create a temporary value, and you simply can't have references to temporary values because of their temporary nature.

Either change doSomething to receive its argument by value, or by const reference (which can bind to a temporary value), or possibly a rvalue-reference (using the && syntax in the argument declaration), or of course make a cast-operator that returns a reference.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621