尝试传递可变数量的初始化程序列表时,我不明白错误消息:
- template<typename... Values>
- void foo(Values...)
- {
- }
- int main()
- {
- foo(1,2,3,"hello",'a'); // OK
- foo({1},{2,3}); // ERROR
- }
- prog.cpp: In function ‘int main()’:
- prog.cpp:9:20: error: too many arguments to function
- ‘void foo(Values ...) [with Values = {}]’
- foo({1},3});
- ^
- prog.cpp:2:6: note: declared here
- void foo(Values...)
- ^
但是,如果我不能通过我想要的论据呢? [ideone link]
解决方法
这个问题很可能是推荐的. {}可以是任何参数的统一初始化器.
这样做:
- #include <initializer_list>
- template<typename... Values>
- void foo(std::initializer_list<Values>... args)
- {
- }
- template<typename... Values>
- void foo(Values&&... args)
- {
- }
- int main()
- {
- foo(1,'a');
- foo({1},3});
- }