我正在尝试使用初始值设定项列表进行完美的转发工作。为了举例,我想要一个可变参数函数来调用另一个函数,并且仍然享受后者的初始化列表的自动转换:
\n#include <iostream> \n#include <vector>\n\nvoid hello(std::string const& text, std::vector<int> const& test)\n{\n std::cout << "hello " << text << " " << test.size() << std::endl; \n}\n\ntemplate<class ... Args>\nvoid f(Args&& ... args)\n{\n return hello(std::forward<Args>(args)...);\n}\n\nint main()\n{\n hello("world", {1,2,3}); // WORKS\n f("world", std::vector<int>({1,2,3})); // WORKS\n f("world", {1,2,3}); // COMPILER ERROR\n}\nRun Code Online (Sandbox Code Playgroud)\n错误是
\nexample.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nexample.cpp:21:21: error: too many arguments to function \xe2\x80\x98void f(Args&& ...) [with Args = {}]\xe2\x80\x99\n 21 | f("world", {1,2,3});\n | ^\nexample.cpp:12:6: note: declared here\n 12 | void f(Args&& ... args)\n | ^\nexample.cpp: In instantiation of \xe2\x80\x98void f(Args&& ...) [with Args = {}]\xe2\x80\x99:\nexample.cpp:21:21: required from here\nexample.cpp:14:15: error: too few arguments to function \xe2\x80\x98void hello(const string&, const std::vector<int>&)\xe2\x80\x99\n 14 | return hello(std::forward<Args>(args)...);\n | ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nexample.cpp:6:6: note: declared here\n 6 | void hello(std::string const& text, std::vector<int> const& test)\n | ^~~~~\nRun Code Online (Sandbox Code Playgroud)\n我在这里犯了任何明显的错误吗?
\n在第三种情况下,编译器无法识别您发送的类型。
如果你使用
f("world", std::initializer_list<int>{1,2,3});
Run Code Online (Sandbox Code Playgroud)
一切正常。
这篇文章有一些详细的解释并引用了标准的相关部分。这是针对略有不同的情况,但解释仍然适用。
| 归档时间: |
|
| 查看次数: |
348 次 |
| 最近记录: |