Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #79325

Re: Overloading the [] operator for read/write...

From Paavo Helde <myfirstname@osa.pri.ee>
Newsgroups comp.lang.c++
Subject Re: Overloading the [] operator for read/write...
Date 2021-04-27 14:02 +0300
Organization A noiseless patient Spider
Message-ID <s68qva$sls$1@dont-email.me> (permalink)
References <s67oai$cm6$1@dont-email.me>

Show all headers | View raw


27.04.2021 04:10 TDH1978 kirjutas:
> I have a database-related class (MyDB) where I would like to overload 
> the [] operator, so that the class looks and behaves like a map.
> 
>    MyDB mydb;  // key-value pairs, like a map
> 
>    //
>    // read from database
>    //
>    X x = mydb[y];
> 
>    //
>    // write to database (using proxy object)
>    //
>    mydb[y] = x;
> 
> 
> Does anyone know how I can do this?
> 
> I tried using a proxy class for the 'write' operation, but when it came 
> time to print a database entry, the compiler would complain that it does 
> not know how to print the proxy object, when in fact it should be 
> printing 'x' from the 'read' operation:
> 
>    cout << mydb[y] << endl;  // compiler error; tries to print proxy 
> object and not 'x'.

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

Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Overloading the [] operator for read/write... TDH1978 <thedeerhunter1978@movie.uni> - 2021-04-26 21:10 -0400
  Re: Overloading the [] operator for read/write... Paavo Helde <myfirstname@osa.pri.ee> - 2021-04-27 14:02 +0300
    Re: Overloading the [] operator for read/write... TDH1978 <thedeerhunter1978@movie.uni> - 2021-04-30 17:08 -0400
      Re: Overloading the [] operator for read/write... Paavo Helde <myfirstname@osa.pri.ee> - 2021-05-02 22:15 +0300
    Re: Overloading the [] operator for read/write... Bonita Montero <Bonita.Montero@gmail.com> - 2021-05-03 09:27 +0200
  Re: Overloading the [] operator for read/write... "daniel...@gmail.com" <danielaparker@gmail.com> - 2021-05-03 07:57 -0700
    Re: Overloading the [] operator for read/write... Paavo Helde <myfirstname@osa.pri.ee> - 2021-05-03 19:13 +0300
      Re: Overloading the [] operator for read/write... "daniel...@gmail.com" <danielaparker@gmail.com> - 2021-05-03 11:33 -0700
      Re: Overloading the [] operator for read/write... David Brown <david.brown@hesbynett.no> - 2021-05-04 18:34 +0200

csiph-web