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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With