struct B
{
};
struct A
{
operator A&() const;
operator B&() const;
};
int main()
{
const A a;
B& br = a;
A& ar = a;
}
Why can I create cast operator to B&, but not to A&.
May be it does not have much sense (one can use it to erase const modifier, as in example), but it at least inconsistent!
You can’t do this because it’s explicitly forbidden. N3290 § 12.3.2 states:
(Emphasis mine)
This is discussed further in a note:
Which explains this decision – it would interfere with the built-in mechanics too much. (For little gain).
If you really want something non-
constfrom aconstobject the only smart way to do this is constructing a new instance using the copy constructor.As a work around you could introduce a lightweight intermediary (like a smart pointer):
But really, wanting to do this in the first place looks like a code smell.