I would like to enforce the type of variadic template to be identical to an earlier set template type. In the below example, I\'d like T and U to be the same type.
c
If all parameters are required to be the same type AND the number of parameters is variable,
Variadic templates are too heavy for those requirements, just use C++11 std::initializer_list.
They just do the job if you can replace () with {} on the call.
template struct Foo {
Foo(T val) {
std::cout << "Called single argument ctor" << std::endl;
}
// Enforce all parameters to be the same type :
Foo( std::initializer_list values ) {
std::cout << "Called multiple argument ctor" << std::endl;
for (T value : values)
cout << value << endl;
}
};
int main() {
// Work as expected.
Foo single(1);
// Work as expected.
Foo multiple{ 1, 2, 3, 4, 5 };
// Doesn't work - as required :
//Foo mixedtype{ 1, "a", "b", "c" };
}