例如,这是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;
正如预期的那样,如果我尝试使用更多数量的参数,我会收到以下错误
$ 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
$
有没有办法声明该类,以便它接受任意数量的模板参数?
答案 0 :(得分:3)
C ++ 11支持variadic templates。这些允许你写:
template<typename ...Args>
class tuple
{
// ...
};
但是,没有简单的方法来迭代可变参数模板的参数。有关此问题的几种解决方法,请参阅链接的文章。