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

查看:73
本文介绍了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;
}

解决方案

因为函数原型就是这样规定的,你写成&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就是干这个的

这篇关于c++ - 为什么调用bind时,不能直接加&amp;,而必须用ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆