如何使用 boost::thread 调用重载函数?

How to call an overloaded function with boost::thread?

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";
    }
 };

在 class 中有像上面那样的重载函数,用 boost::thread newThread(&Foo::method,foo_obj_ptr,a,b 创建一个线程) 抛出错误“没有重载函数需要四个参数”。 [我已将 a 和 b 声明为仅字符。]我的假设是重载函数 boost::thread 无法为此绑定 correctly.Any 解决方案?

我在 vs2010 中使用 boost 1.54。

它与 boost 并没有太大关系,而是与编译器在调用重载函数(在新线程或其他线程中)时理解您指的是哪个函数有关。

这是您的代码 + 使用 std::thread 的解决方案(无重大差异):

#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);
}

注意

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

允许您将第一个参数转换为 thread:

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

这个转换告诉编译器你指的是哪个函数。

只需使用一个带两个 char 的 lambda 函数

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

Live Example.