简体   繁体   中英

c++ 11 - passing member function to thread gives: no overloaded function takes 2 arguments

From what I have looked up, my syntax is correct but my compiler (VS2015) is complaining. Note, I'm using namespace ee with the class Network. Here's the code

    //code that doens't work
    thread clientThread(&ee::Network::clientRun, new ee::Network);

*note: in the real code I'm not calling new as an argument, I did it here to shorten code.

I've tested the functions and they work, I just can't get them to work using thread. Here is their signatures.

    void serverRun();
    void clientRun();
    void clientRun(string ip);

My errors are:

  1. Error C2661 'std::thread::thread': no overloaded function takes 2 arguments

  2. abc no instance of constructor "std::thread::thread" matches the argument list

Does anyone have any insight as to what might be happening in this situation?

Ben's suggestion fixed my problem, but I'm not sure why.

The problem is with the first argument &ee::Network::clientRun . clientRun has 2 overloads, but at the point of template deduction (to deduce the types of the arguments to std::thread::thread<> ) the compiler is not yet in a position to distinguish which of the overloads is more valid.

Ben's solution worked because the cast prior to the call has done the compilers' work for it - by specifying the type of Network::clientRun to be void (ee::Network*)(void) rather than the equally valid void (ee::Network*)(string) .

Some examples:

#include <thread>
#include <string>

struct Network
{
  void clientRun();
  void clientRun(std::string);
};

int main()
{
  // not ok...
//  std::thread clientThread(&Network::clientRun, new Network);

  // ok - tells the compiler which overload
  auto member_function = static_cast<void (Network::*)()>(&Network::clientRun);
  std::thread clientThreadA(member_function, new Network);

  // also ok
  using call_type = void (Network::*)();
  std::thread clientThreadB(call_type(&Network::clientRun), new Network);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM