Lazer
Lazer

Reputation: 94840

How to declare variable number of template arguments?

For example, this is the declaration of boost::tuple

// - tuple forward declaration -----------------------------------------------
template <
  class T0 = null_type, class T1 = null_type, class T2 = null_type,
  class T3 = null_type, class T4 = null_type, class T5 = null_type,
  class T6 = null_type, class T7 = null_type, class T8 = null_type,
  class T9 = null_type>
class tuple;

As expected, I get the following error if I try to use more number of arguments

$ g++ vec.cc 
vec.cc: In function 'int main()':
vec.cc:6: error: wrong number of template arguments (12, should be 10)
/usr/include/boost/tuple/detail/tuple_basic.hpp:75: error: provided for 'template<class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> class boost::tuples::tuple'
vec.cc:6: error: template argument 1 is invalid
vec.cc:6: error: template argument 2 is invalid
vec.cc:6: error: invalid type in declaration before ';' token
$

Is there a way to declare the class so that it accepts any number of template arguments?

Upvotes: 6

Views: 6085

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

C++11 supports variadic templates. These allow you to write:

template<typename ...Args>
class tuple
{
    // ...
};

However, there is no simple way to iterate over the arguments of a variadic template. See the linked article for several workarounds for this problem.

Upvotes: 7

Related Questions