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
  • 12,505
  • 10
  • 59
  • 116

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
  • 94,763
  • 41
  • 167
  • 253
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
  • 301,070
  • 26
  • 186
  • 335
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
  • 33,181
  • 16
  • 123
  • 191
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,927
  • 21
  • 36