Rodolfo Lima wrote:
Hi, I need some help to define a function that accepts a variable
number of parameters of the same type and I wonder if c++0x's
variadic templates would help me.
After looking at c++0x's current draft specification it seems it
isn't possible. I want something along the lines of:
struct A { A(int){} };
template <A... ARGS> void function(ARGS... args) {}
function(A(3), A(2), A(5)); // should be ok
struct B { B(int){} };
function(A(4), B(3), A(1)); // should be an error
Is there a way to accomplish this with variadic templates?
You can extend the is_same test from <type_traits> to work for the
variadic arguments:
// same types?
template<class, class ...> // not defined
struct SameTypes;
template<class ValueT>
struct SameTypes<ValueT> : true_type
{ };
template<class FirstT, class SecondT, class ... ArgTypes>
struct SameTypes<FirstT, SecondT, ArgTypes...>
: public std::integral_constant<bool,
std::is_same<FirstT, SecondT>::value &&
SameTypes<FirstT, ArgTypes...>::value >
{ };
Then you can use a
std::enable_if<SameTypes<ARGS...>::value>
to guard your function.
template <class... ARGS>
requires SameType<A, ARGS>...
void function(ARGS... args) {}
[ comp.lang.c++.moderated. First time posters: Do this! ]