How to use boost async_write with boost const_buffers vector correctly?

I am having trouble getting this line right:

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

vector_ contains the number boost::asio::const_buffers

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

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

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

+7
source share
2 answers

I think you are 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, by the way, is a common function.

+5
source

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

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

Typically, applications never need to use boost::asio::buffer_cast .

+4
source

All Articles