3
#include <thread>
struct Callable
{
    void start() {};
    void start(unsigned) {};
};

int main()
{   
    Callable some_object;
    std::thread some_thread( &Callable::start, &some_object );

    some_thread.join();
}

This code does not compile because &Callable::start is ambiguous. Is there a way to specify which overload should be used in std::thread constructor?

qdii
  • 11,918
  • 9
  • 56
  • 110

4 Answers4

4

You can cast:

using callback_type = void (Callable::*)();

std::thread some_thread(
    static_cast<callback_type>(&Callable::start), &some_object );
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
David G
  • 90,891
  • 40
  • 158
  • 247
2

You can define a pointer to member and use it in the function call

void ( Callable::*p )( unsigned ) = &Callable::start;
std::thread some_thread( p, &some_object );
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
1

You can select between overloads by a cast:

typedef void (Callable::*voidFunc)();

int main()
{   
    Callable some_object;
    std::thread some_thread( (voidFunc)&Callable::start, &some_object );
Suma
  • 31,745
  • 15
  • 120
  • 184
1

According to the second part of this answer, the following would be a safer option:

void (Callable::*)() start_fun = &Callable::start;
std::thread some_thread( start_fun, &some_object );

This is because you avoid the static cast and will get a compiler error on the first line if a matching member function is not found.

Community
  • 1
  • 1
aldo
  • 2,837
  • 20
  • 35