thread-pool icon indicating copy to clipboard operation
thread-pool copied to clipboard

应用层,类的非静态函数不能使用,目前仅静态函数可用

Open dbdxnuliba opened this issue 4 years ago • 3 comments

测试例程如下: class A { public: static int Afun(int n = 0) { std::cout << n << " hello, Afun ! " << std::this_thread::get_id() << std::endl; return n; }

void Cfun(void) {
    std::cout <<  "  hello, Cfun !  "<< "mem_a :"<<mem_a <<"  " << std::this_thread::get_id() << std::endl;
    return ;
}

private: int mem_a=0; }; void test_thread_pool() { // Create pool with 3 threads,max_thr_num:100 //同时存活的线程的最小数量3,同时存活的线程的最大数量100 ThreadPool pool(1,2);

// Initialize pool
pool.init();

std::cout << "main thread id :"<<std::this_thread::get_id()<< std::endl;

 std::future<int> gg = pool.submit(A::Afun, 9999);//静态函数成功
 A A_obj;
std::future<int> hh = pool.submit(A_obj.Cfun,); //非静态函数不成功

}

: error: invalid use of non-static member function std::future hh = pool.submit(A_obj.Cfun); ^

dbdxnuliba avatar May 11 '21 06:05 dbdxnuliba

经过查找资料可以这么实现,强制转换成员函数为普通函数 A A_obj; typedef void* (FUNC)(void,int); //FUNC callback = (FUNC)&A::Cfun;//强制转换func()的类型 FUNC callback = (FUNC)&A::Cfun;//强制转换func()的类型 pool.submit(callback,&A_obj,1);

dbdxnuliba avatar May 11 '21 07:05 dbdxnuliba

可以这样写,一步到位:pool.submit(std::bind(&A::func, A_obj))

经过查找资料可以这么实现,强制转换成员函数为普通函数 A A_obj; typedef void* (FUNC)(void,int); //FUNC callback = (FUNC)&A::Cfun;//强制转换func()的类型 FUNC callback = (FUNC)&A::Cfun;//强制转换func()的类型 pool.submit(callback,&A_obj,1);

chanwoood avatar Feb 16 '23 06:02 chanwoood

厉害

dbdxnuliba avatar Mar 02 '23 15:03 dbdxnuliba