Jook
Jook

Reputation: 4682

How to use boost async_write with a vector of boost const_buffers correctly?

I am having trouble to make this line here right:

boost::asio::async_write(serialPort, 
                         boost::asio::buffer(
                         boost::asio::buffer_cast<const void*>(vector_.front()),
                         boost::asio::buffer_size(vector_.front())))

vector_ holds a number of boost::asio::const_buffers

std::vector<boost::asio::const_buffer> vector_;

This stuff works, but I am quite sure that there is a way more elegant way to do this, and if not, I would like to here that from someone with a bit more experience.

So, can this solution be improved? If so, how?

Upvotes: 7

Views: 2485

Answers (2)

Tanner Sansbury
Tanner Sansbury

Reputation: 51871

The elegant way is to pass the buffer directly to boost::asio::buffer. One of its overloadeds takes a single boost::asio::const_buffer and returns a type that can be used in boost::asio::async_write, as it meets the requirements of the ConstBufferSequence concept.

boost::asio::async_write(serialPort, boost::asio::buffer(vector_.front()));

As a general rule, applications should never need to use boost::asio::buffer_cast.

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361252

I think you're looking for this:

boost::asio::async_write(serialPort, make_buffer(vector_.front()) );

where make_buffer is defined as:

template<typename TBuffer>
boost::asio::buffer make_buffer(TBuffer & data)
{
   auto buf = boost::asio::buffer_cast<const void*>(data);
   auto size= boost::asio::buffer_size(data);
   return boost::asio::buffer(buf, size);
}

which is a generic function by the way.

Upvotes: 5

Related Questions