Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dbdxnuliba opened this issue May 11, 2021 · 3 comments

Comments

@dbdxnuliba
Copy link

测试例程如下:
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
Copy link
Author

经过查找资料可以这么实现,强制转换成员函数为普通函数
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
Copy link

可以这样写,一步到位: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);

@dbdxnuliba
Copy link
Author

厉害

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants