0

Found:
Ambiguity while overloading the cast operator

and

C++ Operator Ambiguity

not helpful

Situation:

Inside the container class's body I have:

operator T& () const {
    return *data;
}

operator const T& () const {
    return *data;
}

The intent being that:

container<object> test = new object;
object& whatever = test; //<--uses (T&) cast
const object& other = test; //<--uses (const T&) cast

However the second one causes an error because it is ambiguous.

I completely see why the compiler is complaining, it is okay to assign a object& and a const object& to a const object& however I'd like it to not complain and choose the second (return const object&)

Oh wait, just got my answer.

Community
  • 1
  • 1
Alec Teal
  • 5,770
  • 3
  • 23
  • 50

2 Answers2

5

Even though they're different conversion operators (not just overloads of one), the ambiguity is resolved by removing the const you have on the first one.

Thus:

operator T& () {
    return *data;
}

operator const T& () const {
    return *data;
}

Alternatively, if it really makes sense to provide non-const access to the pointed to data via a const object, then just do

operator T& () const {
    return *data;
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

Stop being silly. As I said you may assign a object& or a const object& to a const object& so the first cast operator is sufficient for the job in either case.

Silly me. Hope this helps someone in the future!

Alec Teal
  • 5,770
  • 3
  • 23
  • 50
  • 2
    Depending on the semantics you want (whether the data held by a `const` container should be mutable), it may make more sense to make the first overload non-`const` instead. – T.C. Jul 15 '14 at 03:33