3

I'm trying to use std::bind in Qt 5.1 and MSVC 2010 to hook a QNetworkReply event to a member function while passing the reply as a parameter. Directly putting the std::bind in the connect line fails with a ton of template errors on MSVC 2010 but splitting this into two lines by using std::function works. I'd love to stick with one line. What is the magic incantation to make this happen?

void MyClass::doRequest ( )
{

    ..

    QNetworkReply * reply = nam.get(...)

    // next line fails on MSVC 2010
    connect(reply, &QNetworkReply::finished, std::bind(&MyClass::onNetworkDone, this, reply));

    // next two lines do work on MSVC 2010  
    std::function<void ()> a = std::bind<void()>(&MyClass::onNetworkDone, this, reply);
    connect(reply, &QNetworkReply::finished, a);
}

void MyClass::onNetworkDone( QNetworkReply * reply )
{
    ..
}
user815719
  • 43
  • 1
  • 2
  • 4
  • 1
    The 2-line solution compiles, but does it works? I believe the result of bind must be stored in a permanent container which must not have been deleted at the time the function is called. The one line solution does not compile because the compiler sees you are doing something wrong, whether in the other case you mask it. Maybe I'm totally wrong. – galinette Sep 20 '13 at 17:11

1 Answers1

2

You need to cast the bind to a function pointer with:

connect(reply, &QNetworkReply::finished, (void(*)()) std::bind(&MyClass::onNetworkDone, this, reply));

This answers your question. However, I'm not sure it won't crash at runtime, for the reason discussed in the above comment.

galinette
  • 8,896
  • 2
  • 36
  • 87