Reputation: 5550
I'd like to find a single asio::buffer type / constructor that I can use to send both std::string
and std::vector
objects via asynch_send_to
.
Please note that I'm using standalone asio, without boost!
Right now the function I'm using to send data is:
void UdpSocket::send_datagram(asio::const_buffer buffer) {
mSocket.async_send_to(buffer, mEndpoint,
[this, datagram](const asio::error_code& error, std::size_t bytes_transferred) {
if (!error) {
// stuff...
}
else{
// other stuff..
}
});
}
I'd like to be able to use either:
std::vector mVector;
send_datagram(asio::buffer(mVector.data(), mVector.size());
or
std::string mString = "hello world";
send_datagram(asio::buffer(mString.data(), mString.length());
The above gives me a sequence of errors in buffer_sequence_adapter.hpp
:
I'm a bit overwhelmed by the sheer number of buffers and the compatibility between them; can someone help me sort out what is the right type of buffer / constructor to use that can take both std::vector
and std::string
types?
thanks!
Upvotes: 1
Views: 1376
Reputation: 7357
You can accept buffer pointer & length as a parameter, this probably is the most extendable way:
void UdpSocket::send_datagram(const char *buf, size_t len) {
mSocket.async_send_to(asio::buffer(buf, len), mEndpoint,
[this, datagram](const asio::error_code& error, std::size_t bytes_transferred) {
This enables you to use nearly any storage for this, for convenience you can write simple overload(s) like this:
void send_datagram(const std::string &s) { send_datagram(s.c_str(), s.size()); }
void send_datagram(const std::vector<char> &s) { send_datagram(s.data(), s.size()); }
But in this snippets you should keep in mind some things:
Upvotes: 1