How can I do the equivalent of:
#include <vector>
size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer(bufferSize, ' ');
With list (curly braced) initialization?
When I try to do the following:
#include <vector>
size_t bufferSize = 1024 * 1024;
std::vector<unsigned char> buffer {bufferSize, ' '};
It wrongly interprets bufferSize
as the value to be stored in the first index of the container (i.e. calls the wrong std::vector
constructor), and fails to compile due to invalid narrowing conversion from unsigned int
(size_t
) to unsigned char
.
Short answer: you don't.
This is not a problem with uniform initialization per se, but with std::initializer_list
. There is a special rule in overload resolution that always gives priority to constructors taking std::initializer_list
if list-initialization is used, regardless of the existence of other constructors which might require less implicit conversions.
I would suggest using
std::vector<unsigned char> buffer(bufferSize, ' ');
or, if you really want to use list-initialization, create your wrapper around std::vector
that provides constructor overloads that do the right thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With