将函数应用于参数包
我正在玩参数包,并且我正在尝试通过lambda函数应用映射,该函数将1
添加到参数包的每个成员,如图所示。但是,我获得了输出4
,而234
则可以。
#include <iostream>
// method to print a variadic list of arguments
template<typename... Args>
void print(const Args &... args) {
(std::cout << ... << args) << std::endl;
}
// transform each element of argument list
// and then perfect forward the result
template<typename F, typename... Args>
auto mapping(F f, Args &&... args) {
return (f(std::forward<Args>(args)), ...);
}
int main() {
print(1,2,3); // 123 (OK)
print(mapping([](auto &&a) {return a + 1;}, 1, 2, 3)); // 4 (!) (234 expected)
}
如何通过映射参数包1,2,3
- &gt; 2,3,4
to variadic函数print
?
I'm playing around with parameter packs, and I'm trying to apply a mapping via a lambda function which adds 1
to each member of the parameter pack as shown. However, I get the output 4
while 234
is expected.
#include <iostream>
// method to print a variadic list of arguments
template<typename... Args>
void print(const Args &... args) {
(std::cout << ... << args) << std::endl;
}
// transform each element of argument list
// and then perfect forward the result
template<typename F, typename... Args>
auto mapping(F f, Args &&... args) {
return (f(std::forward<Args>(args)), ...);
}
int main() {
print(1,2,3); // 123 (OK)
print(mapping([](auto &&a) {return a + 1;}, 1, 2, 3)); // 4 (!) (234 expected)
}
How do I pass the mapped parameter pack 1,2,3
--> 2,3,4
to the variadic function print
above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法返回参数包。最接近的是
std :: tuple
。类似的内容:
您需要修改打印功能才能接受元组。
You can't return a parameter pack. The closest thing is
std::tuple
.Something like this:
You'll need to modify your printing function to accept tuples too.