Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializer_list combined with other parameters

Suppose I have a class which takes a parameter of type T and a collection of parameters of type U in the constructor. The following solution works:

struct Q
{
    Q(T t, std::initializer_list<U> us);
};

Creating an instance of this class would then be:

Q q {t1, {u1, u2, u3, u4} };

But this looks kind of unclean to me. Is there a better solution than this one?

like image 494
Marius Herzog Avatar asked Sep 06 '14 09:09

Marius Herzog


1 Answers

What you need is variadic templates (c++11 feature).

#include <initializer_list>

struct T {};
struct U {};

class Q {
 public:
  template <class ...ArgTypes>
  Q(T t, ArgTypes... args) : Q(t, {args...}) {}
 private:
  Q(T t, std::initializer_list<U> us) {}
};

int main() {
  T t1;
  U u1, u2, u3, u4;
  Q {t1, u1, u2, u3, u4};
}

It's still typesafe - only structures of type U are allowed.

like image 75
Maciej Chałapuk Avatar answered Sep 23 '22 14:09

Maciej Chałapuk