c++ - Initializing fixed number of variables with an initializer list -
i want initialize object initializer list. problem is, initializer list able contain unpredictable number of elements, need initialize variables. user may send number of list elements, , need 4 of them.
i wrote following code, looks long , inefficient me. there better way of doing this?
pixel::pixel(std::initializer_list<uint8_t> channels) { switch (channels.size()) { case 0: r = 0; g = 0; b = 0; = 0; break; case 1: r = *(channels.begin() + 0); g = 0; b = 0; = 0; break; case 2: r = *(channels.begin() + 0); g = *(channels.begin() + 1); b = 0; = 0; break; case 3: r = *(channels.begin() + 0); g = *(channels.begin() + 1); b = *(channels.begin() + 2); = 0; break; default: r = *(channels.begin() + 0); g = *(channels.begin() + 1); b = *(channels.begin() + 2); = *(channels.begin() + 3); } }
(note: know can done passing r, g, b, values 4 separate arguments. main purpose learn how initializer list feature.)
the best come when using std::initialiser_list
struct pixel { pixel(std::initializer_list<uint8_t> rgba) : _rgba { rgba } { switch(_rgba.size()) { case 0: _rgba.push_back(0); case 1: _rgba.push_back(0); case 2: _rgba.push_back(0); case 3: _rgba.push_back(0); case 4: break; default: throw std::invalid_argument { "" }; } } std::vector<uint8_t> _rgba; };
... ...
probably correct way solve problem this:
struct pixel { pixel(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t = 0) : r(r) , g(g) , b(b) , a(a) {} uint8_t r,g,b,a; };
because
- it fail compile if provide invalid arguments
- it's optimally efficient
- it's least surprising solution maintaining code
- it automatically supports initializer_list syntax @ call site
examples:
int main() { pixel p1 { 10, 20, 5, 255 }; pixel p2 { 10, 20, 5 }; pixel p3 { 10, 20 }; pixel p4 { 10 }; pixel p5 { }; pixel pv1 ( 10, 20, 5, 255 ); pixel pv2 ( 10, 20, 5 ); pixel pv3 ( 10, 20 ); pixel pv4 ( 10 ); pixel pv5; return 0; }
Comments
Post a Comment