如题
#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;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因为函数原型就是这样规定的,你写成
&cout
就是个指针了,当然非法;用std::ref
包裹一下就符合原型要求了,相当于传个引用进去,同样还有不可变的std::cref
,下面是官方对于参数类型的要求:你看最后一行,说要求得是个
reference_wrapper
,std::ref
和std::cref
就是干这个的