So I've browsed a bunch of other threads, but none pertain to the questions I have on this exact topic. I am writing a C++ library to do socket communication. I have a TCP socket class which handles all operations on a TCP socket (setup, read/write, etc). I want to be able to read and write data to/from a TCP socket object using the << and >> operators. For example, I want to be able to write, say, a double to the socket in this fashion:
double x;
TcpSocket *sock = new TcpSocket();
//socket setup stuff here...
sock << x;
At the moment, I have two templated overloaded operator functions within the 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( ) and sock.Write( ) issue the system calls read( ) and write( ) using a socket file descriptor (not really relevant but just FYI). These functions are templated in an attempt to be able to get the bytes for almost any data type in one place.
So my questions are:
- Will these overloaded operator functions work in the way I want them to?
If it works, can I chain these together, such as:
sock << 45.8 << 33.9 << "numbers";
========================================================================= Here are my updated operator functions:
//Write to 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 from 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;
}