将函数应用于参数包

发布于 2025-02-13 19:12:28 字数 828 浏览 0 评论 0原文

我正在玩参数包,并且我正在尝试通过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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偷得浮生 2025-02-20 19:12:28

您无法返回参数包。最接近的是std :: tuple

类似的内容:

template<typename F, typename ...Args>
auto mapping(F f, Args &&... args)
{
    // Note `{...}` instead of `(...)`, forcing the call order of `f`.
    return std::tuple{f(std::forward<Args>(args))...};
}

您需要修改打印功能才能接受元组。

You can't return a parameter pack. The closest thing is std::tuple.

Something like this:

template<typename F, typename ...Args>
auto mapping(F f, Args &&... args)
{
    // Note `{...}` instead of `(...)`, forcing the call order of `f`.
    return std::tuple{f(std::forward<Args>(args))...};
}

You'll need to modify your printing function to accept tuples too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文