jiopaley jiopaley - 1 year ago 96
C++ Question

Is it possible to construct a boost::circular_buffer with a braced initialiser list?

The following fails to compile:

auto myCircularBuffer = boost::circular_buffer<int>{1,2,3,4};

with error:

`error: no matching function for call to ‘boost::circular_buffer<int>::circular_buffer(<brace-enclosed initializer list>)’`

Is there another mechanism for constructing the boost::circular_buffer with a braced initialiser list or perform another form of aggregate initialisation? Or do we have to push_back each element?

Answer Source

From looking at the docs, circular_buffer doesn't have an initializer list overload. The only real alternative to pushing items one at a time would be the InputIterator, InputIterator overload.

Of course, you're free to make your own function that uses the InputIterator, InputIterator overload to let you use initializer lists:

template<typename T>
boost::circular_buffer<T> make_circular_buffer(const std::initializer_list<T>& init)
  return boost::circular_buffer<T>(init.begin(), init.end());

auto b = make_circular_buffer({1,2,3,4});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download