Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does std::thread throws an error when it's asked to run an overloaded function?

below is the code i am running , it throws an error in the lines where i am passing overloaded function 'myfunc' in thread object t1 and t2 (also identified with a comment)

#include<iostream>
#include<thread>
using namespace std;

    void  myfunc(int x)
        {
            cout << x << endl;
        }

    void  myfunc(int  x,int y)
    
    {
        
        cout << x << " " << y << endl;
    }

    int main()
    {
    
        thread t1(myfunc,1);//error here
        thread t2(myfunc, 1,2);//error here
        
        t1.join();
        t2.join();
        return 0;
    }

The error statement:

Error 1: Error (active) E0289 no instance of constructor "std::thread::thread" matches the argument list arguments type are: (unknown-type,int)

Error 2: Error (active) E0289 no instance of constructor "std::thread::thread" matches the argument list arguments type are: (unknown-type,int,int)

like image 322
abdullah naeem Avatar asked Feb 08 '26 00:02

abdullah naeem


1 Answers

When you have overloaded functions that you pass as arguments, you need to help the compiler.

Possible solution:

using f1 = void(*)(int);
using f2 = void(*)(int, int);

thread t1(static_cast<f1>(myfunc), 1);
thread t2(static_cast<f2>(myfunc), 1, 2);
like image 172
Ted Lyngmo Avatar answered Feb 09 '26 13:02

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!