【问题标题】:How to pass a reference through a parameter pack?如何通过参数包传递引用?
【发布时间】:2012-02-24 13:28:15
【问题描述】:

我有以下代码:

#include <cstdio>

template<class Fun, class... Args>
void foo(Fun f, Args... args)
{
    f(args...);
}

int main()
{
    int a = 2;
    int b = 1000;

    foo([](int &b, int a){ b = a; }, b, a);
    std::printf("%d\n", b);
}

目前它打印1000,即b 的新值在某处丢失。我猜那是因为foo 按值传递参数包中的参数。我该如何解决?

【问题讨论】:

    标签: c++ reference c++11 variadic-templates


    【解决方案1】:

    通过使用参考:

    template<class Fun, class... Args>
    void foo(Fun f, Args&&... args)
    {
        f( std::forward<Args>(args)... );
    }
    

    【讨论】:

    • 如果a 是一个右值,这将失败,即使这在语义上应该是允许的。 &amp;&amp; 我觉得会更好。
    • 如果使用&amp;&amp;,完全符合我的需求。
    • 你应该转发:f(std::forward&lt;Args&gt;(args)...);
    • @GMan : +1 我也打算在这里建议使用forward&lt;&gt;,但我不知道转发参数包的语法。 :-[
    【解决方案2】:

    像这样:

    #include <iostream>
    #include <functional>
    
    template<class Fun, class... Args>
    void foo(Fun f, Args... args)
    {
        f(args...);
    }
    
    int main()
    {
        int a = 2;
        int b = 1000;
    
        foo([](int &b, int a){ b = a; }, std::ref(b), a);
        std::cout << b << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2015-07-06
      • 1970-01-01
      • 2011-08-21
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多