search

Home  >  Q&A  >  body text

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 days ago584

reply all(1)I'll reply

  • 天蓬老师

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

    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

    reply
    0
  • Cancelreply