sockets - C++ overload << operator for class object acting as stream -
so i've browsed bunch of other threads, none pertain questions have on exact topic. writing c++ library socket communication. have tcp socket class handles operations on tcp socket (setup, read/write, etc). want able read , write data to/from tcp socket object using << , >> operators. example, want able write, say, double socket in fashion:
double x; tcpsocket *sock = new tcpsocket(); //socket setup stuff here... sock << x;
at moment, have 2 templated overloaded operator functions within tcpsocket class:
template<typename t> tcpsocket operator<<(tcpsocket sock, t &val) { unsigned char bytesofval[] = //parse bytes of val here... sock.write(bytesofval, sizeof(bytesofval)); }
-
template<typename t> tcpsocket operator>>(tcpsocket sock, t &val) { std::stringstream ss; byte buf[sizeof(val)]; sock.read(buf, sizeof(buf)); ss.str(std::string(buf)); ss >> val; }
where sock.read( ) , sock.write( ) issue system calls read( ) , write( ) using socket file descriptor (not relevant fyi). these functions templated in attempt able bytes data type in 1 place.
so questions are:
- will these overloaded operator functions work in way want them to?
if works, can chain these together, such as:
sock << 45.8 << 33.9 << "numbers";
========================================================================= here updated operator functions:
//write socket template<typename t> tcpsocket& operator<<(tcpsocket& sock, t &val) { size_t buflen = sizeof(val); unsigned char buf[buflen]; memcpy(buf, &val, buflen); sock.write(buf, buflen); return sock; }
and
//read socket template<typename t> tcpsocket& operator>>(tcpsocket &sock, t &val) { size_t buflen = sizeof(val); unsigned char buf[buflen]; int numbytesread = 0; numbytesread = sock.read(buf, buflen); memcpy(&val, buf, numbytesread); return sock; }
for function work @ all, you'll need use references tcpsocket
input argument return type. val
needs t const&
, not t&
.
template<typename t> tcpsocket& operator<<(tcpsocket& sock, t const&val) { unsigned char bytesofval[] = //parse bytes of val here... sock.write(bytesofval, sizeof(bytesofval)); return sock; }
now, can use:
sock << 45.8 << 33.9 << "numbers";
if want able use:
sock << 45.8 << 33.9 << "numbers" << std::endl;
you'll need function.
tcpsocket& operator<<(tcpsocket& soc, std::ostream&(*f)(std::ostream&)) { std::ostringstream s; s << f; return sock << s.str(); }
Comments
Post a Comment