c++ - 为什么调用bind时,不能直接加&,而必须用ref
PHP中文网
PHP中文网 2017-04-17 14:24:58
0
1
571

如题

#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中文网

认证高级PHP讲师

reply all(1)
Peter_Zhu

Because the function prototype is stipulated in this way, if you write it as &cout, it will be a pointer, which is of course illegal; wrapping it with std::ref will meet the prototype requirements, which is equivalent to passing a reference in, and there is also an immutable std::cref, the following are the official requirements for parameter types:

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.

Look at the last line, it says the request must be a reference_wrapper, that’s what std::ref and std::cref do

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template