01.05.2021 00:08 TDH1978 kirjutas:
> On 2021-04-27 11:02:01 +0000, Paavo Helde said:
>
>> You need to add a streaming operator for your proxy. Something like:
>>
>> std::ostream& operator<<(std::ostream& os, const Proxy& proxy) {
>> os << proxy.get_value();
>> return os;
>> }
>
> Thank you; I'm sure that would work, but I would have expected
> operator<<() to prefer the 'const':
>
> X operator[](const Y& y) const
>
> over the 'non-const':
>
> MyDBProxy_& operator[](const Y& y)
>
Which operator<<()? I your example there was none, and there is no default.
I guess you mean the line:
> cout << mydb[y] << endl; // compiler error; tries to print proxy
object and not 'x'.
Here, operator[] is called before passing the result to any operator<<,
existing or not. IOW, the meaning of 'mydb[y]' does not change depending
on the expression where it appears in.
Whether a const or non-const overload is preferred, is determined simply
by if 'mydb' is const or non-const. You can always cast to const if
that's what you need:
const MyDB& cmydb = mydb;
cout << cmydb[y] << endl
> Do you know why the compiler is choosing one over the other?
>
> What if, instead of operator<<(), I had a function:
>
> void foo(const X& x);
>
> and I pass it:
>
> foo(mydb[y]);
>
> Would the compiler complain because it thinks mydb[y] returns the proxy
> and not x?
Why don't you try out and see it by yourself what happens? Such
experiments are a must if you want to understand how a language works.