无法将多个初始化列表传递给可变函数模板 [英] Having trouble passing multiple initializer lists to variadic function template

查看:160
本文介绍了无法将多个初始化列表传递给可变函数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试传递可变数量的初始值列表时,我不明白错误消息:

I don't understand the error message when trying to pass a variable number of initializer lists:

template<typename... Values>
void foo(Values...)
{
}

int main()
{
    foo(1, 2, 3, "hello", 'a');   // OK

    foo({1}, {2, 3});             // ERROR
}

错误消息提示参数过多:

The error message complains about too many arguments:

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

但是,我是否应该不能传递尽可能多的参数? [ ideone link ]

However, should I not be able to pass as many arguments as I want? [ideone link]

推荐答案

问题很可能是推论。 {} 可以是任何参数的统一初始化。

The problem is likely deducibility. {} could be uniform initializers to any of the arguments.

这适用于:

#include <initializer_list>

template<typename... Values>
void foo(std::initializer_list<Values>... args)
{
}

template<typename... Values>
void foo(Values&&... args)
{
}

int main()
{    
    foo(1, 2, 3, "hello", 'a');
    foo({1}, {2, 3});
}

查看 Lives on Coliru

See it Live on Coliru

这篇关于无法将多个初始化列表传递给可变函数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆