Search code examples
c++c++11initialization

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?


Solution

  • 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.