Initializer_list in combination with other parameters

Suppose I have a class that accepts a type parameter Tand a set of type parameters Uin the constructor. The following solution works:

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

Creating an instance of this class will be as follows:

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

But for me it looks unclean. Is there a better solution than this?

+4
source share
1 answer

You need variable templates (C ++ 11 function).

#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 is still typeafe - only type structures are allowed U.

+8
source

All Articles