3
class Foo
{
public:
    void method(int a,float b)
    {
        cout<<"This method takes float and int";
    }
    void method(char a,char b)
    {
        cout<<"This method takes two characters";
    }
 };

In a class with overloaded functions like the one above,creating a thread with boost::thread newThread(&Foo::method,foo_obj_ptr,a,b) throws the error " No overloaded function takes four arguments " . [ I have declared a and b as characters only.] My assumption is that with an overloaded function boost::thread is unable to bind correctly.Any solutions for this ?

I am using boost 1.54 with vs2010.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
J V
  • 515
  • 1
  • 5
  • 15

2 Answers2

4

It doesn't have really much to do with boost, but rather with the compiler understanding which function you mean when you call an overloaded function (in a new thread or otherwise).

Here is your code + a solution using std::thread (no major difference):

#include <thread>
#include <iostream>

using namespace std;

class Foo
{
public:
    void method(int a,float b)
    {
        cout<<"This method takes float and int";
    }
    void method(char a,char b)
    {
        cout<<"This method takes two characters";
    }
 };


int main()
{
    Foo foo;
    typedef void (Foo::*fn)(char, char);
    thread bar((fn)(&Foo::method), &foo, 2, 3);
}

Note the

typedef void (Foo::*fn)(char, char);

which allows you to cast the first argument to thread:

thread bar((fn)(&Foo::method), &foo, 'b', 'c');

This cast tells the compiler which of the functions you mean.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • C++ really needs to learn to pass templates and overloaded functions. Manual function overload resolution is so error prone and unnecessary. – nwp Jun 23 '15 at 07:04
  • @Puppy No you cannot. When passing an overloaded function and it "works", you just passed a specific function chosen by overload resolution. You cannot pass multiple functions in an "overloaded function type" and do overload resolution later. In my opinion you should be. Same with templates. The question has an example where you cannot pass an overloaded member function to `boost::thread`, it must be a specific one. – nwp Jun 23 '15 at 16:34
2

Just use a lambda function taking two chars

int main()
{
    Foo foo;
    thread yay([&foo](char a, char b){ foo.method(a, b); }, 2, 3);
    yay.join();
}

Live Example.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • You could simply pass the parameters directly in the lambda instead of passing them to thread to pass them to the lambda. – Puppy Jun 23 '15 at 08:58
  • @Puppy like how? the problem is that passing 2,3 to `method` will select the `int, float` overload because it is a better match during overload resolution – TemplateRex Jun 23 '15 at 09:00