I want to initialize an object with an initializer list. The problem is, an initializer list is able to contain unpredictable number of elements, but I need to initialize only for variables. The user may send any number of list elements, and I need only four of them.
I wrote the following code, but it looks like very long and inefficient to me. Is there any better way of doing this?
Pixel::Pixel(std::initializer_list<uint8_t> Channels)
{
switch (Channels.size())
{
case 0:
R = 0;
G = 0;
B = 0;
A = 0;
break;
case 1:
R = *(Channels.begin() + 0);
G = 0;
B = 0;
A = 0;
break;
case 2:
R = *(Channels.begin() + 0);
G = *(Channels.begin() + 1);
B = 0;
A = 0;
break;
case 3:
R = *(Channels.begin() + 0);
G = *(Channels.begin() + 1);
B = *(Channels.begin() + 2);
A = 0;
break;
default:
R = *(Channels.begin() + 0);
G = *(Channels.begin() + 1);
B = *(Channels.begin() + 2);
A = *(Channels.begin() + 3);
}
}
(Note: I know this can be done with passing the R, G, B, A values with four separate arguments. But my main purpose is to learn how to do this with the initializer list feature.)
std::array<>.const std::array<uint8_t, 4>&?Pixel::Pixel(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 0)? It's simple and runs on anything on or above C++03 and doesn't force the client code to create an array.