C++11 使用代理将成员函数传递给线程

C++11 pass a member function to a thread using a proxy

本文关键字:线程 函数 成员 代理 C++11      更新时间:2023-10-16

我尝试生成一种通用方法来创建具有 argunment a class 方法的线程。但是我无法成功编译代码我使用以下代码

#include <iostream>
#include <thread>
#include <functional>
using namespace std;
class hello{
public:
    void f(){
        cout<<"f"<<endl;
    }
    virtual void ff(){
        cout<<"ff"<<endl;
    }
};
template <typename T, T> struct proxy;
template <typename T, typename R, typename ...Args, R (T::*mf)(Args...)>
struct proxy<R (T::*)(Args...), mf>
{
    static R call(T & obj, Args &&... args)
    {  
    //    function func = T::*mf;
        thread t(&T::*mf, &obj);
        return (obj.*mf)(std::forward<Args>(args)...);
    }
};
int main(){
    hello obj;
   typedef proxy<void(hello::*)(), &hello::f> hello_proxy;
   hello_proxy::call(obj);
}

编译时生成以下错误

In static member function 'static R proxy<R (T::*)(Args ...), mf>::call(T&, Args&& ...)':
24:22: error: expected unqualified-id before '*' token
    thread t(&T::*mf, &obj);

&T::*mf是错误的语法。 只需使用mf.

    thread t(mf, &obj);