gpt4 book ai didi

c++11线程类如何使用类成员函数

转载 作者:IT老高 更新时间:2023-10-28 21:54:14 29 4
gpt4 key购买 nike

我的程序如下所示

#include <iostream>
#include <thread>

class A {
public:
void foo(int n ) { std::cout << n << std::endl; }
};

int main()
{
A a;

std::thread t1(&A::foo, std::ref(a), 100);

t1.join();
return 0;
}

当我使用以下命令编译它时,我得到了错误

g++ -o main main.cc -lpthread -std=c++11

错误:

In file included from /usr/local/include/c++/4.8.2/thread:39:0,
from check.cc:2:
/usr/local/include/c++/4.8.2/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (A::*)(int)>(std::reference_wrapper<A>, int)>’:
/usr/local/include/c++/4.8.2/thread:137:47: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (A::*)(int); _Args = {std::reference_wrapper<A>, int}]’
check.cc:13:42: required from here
/usr/local/include/c++/4.8.2/functional:1697:61: error:no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (A::*)(int)>(std::reference_wrapper<A>, int)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/local/include/c++/4.8.2/functional:1727:9: error:no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (A::*)(int)>(std::reference_wrapper<A>, int)>’
_M_invoke(_Index_tuple<_Indices...>)
^

最佳答案

这不是引用包装器的正确位置。不过,一个简单的指针就足够了,并且可以达到预期的效果:

std::thread t1(&A::foo, &a, 100);

关于c++11线程类如何使用类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21059115/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com