搜尋

首頁  >  問答  >  主體

c++ - 为什么调用bind时,不能直接加&,而必须用ref

如题

#include <iostream>
#include <functional>
using namespace std;
void g(ostream &os)
{
    os << "1";
}
int main()
{
    //非法
    auto f = bind(g, &cout);
    f();
    //合法
    auto h = bind(g, ref(cout));
    h();
    return 0;
}
PHP中文网PHP中文网2808 天前583

全部回覆(1)我來回復

  • 天蓬老师

    天蓬老师2017-04-17 14:26:58

    因為函數原型就是這樣規定的,你寫成&cout就是個指針了,當然非法;用std::ref包裹一下就符合原型要求了,相當於傳個引用進去,同樣還有不可變的std::cref,以下是官方對於參數類型的要求:

    fn
    A function object, pointer to function or pointer to member.
    Fn shall have a decay type which is move-constructible from fn.
    
    args...
    List of arguments to bind: either values, or placeholders.
    The types in Args... shall have decay types which are move-constructible from their respective arguments in args....
    If for any argument, its decay type is a reference_wrapper, it bounds to its referenced value instead.

    你看最後一行,說要求得是個reference_wrapperstd::refstd::cref就是乾這個的

    回覆
    0
  • 取消回覆