c – 将多个初始化器列表传递给可变函数模板有困难

前端之家收集整理的这篇文章主要介绍了c – 将多个初始化器列表传递给可变函数模板有困难前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试传递可变数量的初始化程序列表时,我不明白错误消息:
  1. template<typename... Values>
  2. void foo(Values...)
  3. {
  4. }
  5.  
  6. int main()
  7. {
  8. foo(1,2,3,"hello",'a'); // OK
  9.  
  10. foo({1},{2,3}); // ERROR
  11. }

错误信息抱怨太多参数

  1. prog.cpp: In function int main()’:
  2. prog.cpp:9:20: error: too many arguments to function
  3. void foo(Values ...) [with Values = {}]’
  4. foo({1},3});
  5. ^
  6. prog.cpp:2:6: note: declared here
  7. void foo(Values...)
  8. ^

但是,如果我不能通过我想要的论据呢? [ideone link]

解决方法

这个问题很可能是推荐的. {}可以是任何参数的统一初始化器.

这样做:

  1. #include <initializer_list>
  2.  
  3. template<typename... Values>
  4. void foo(std::initializer_list<Values>... args)
  5. {
  6. }
  7.  
  8. template<typename... Values>
  9. void foo(Values&&... args)
  10. {
  11. }
  12.  
  13. int main()
  14. {
  15. foo(1,'a');
  16. foo({1},3});
  17. }

Live on Coliru

猜你在找的C&C++相关文章