我知道已经有人问过这种类型的问题,但我无法找出我遇到错误的原因..
我正在尝试使用多个线程测试如下所示的锁定实现:
class TTAS
{
atomic<bool> state;
public:
TTAS(){
state = ATOMIC_FLAG_INIT;
}
void lock() {
while(true) {
while(state) {};
// using exchange() which is equivalent to getAndSet but with lookup
if (!state.exchange(true)) {
return;
}
}
}
void unlock() {
state.exchange(false);
}
};
我正在使用以下代码为此创建线程:
void test2(TTAS t) {
}
TTAS t();
for (int i = 0; i < 10; i++) {
// Create a thread and push it into the thread list and call the distributedWrite function
threadList.push_back(std::thread(test2, std::ref(t)));
}
当我编译这段代码时,出现以下错误。我不知道我在这里做错了什么..
In file included from /usr/include/c++/5/thread:39:0,
from assgn4.cpp:17:
/usr/include/c++/5/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::reference_wrapper<TTAS()>))(TTAS)>’:
/usr/include/c++/5/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(TTAS); _Args = {std::reference_wrapper<TTAS()>}]’
assgn4.cpp:186:60: required from here
/usr/include/c++/5/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::reference_wrapper<TTAS()>))(TTAS)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/5/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::reference_wrapper<TTAS()>))(TTAS)>’
_M_invoke(_Index_tuple<_Indices...>)
^
有人可以解释这个错误吗?提前致谢
最佳答案
您似乎遇到了 most vexing parse
TTAS t();
t
是一个不带参数并返回 TTAS
的函数.
与传统语法相比,更喜欢统一初始化1 语法:
TTAS t{}; // no ambiguity here
您的代码还有一个问题 test2
按值获取参数,但是 TTAS
包含 std::atomic<bool>
既不可复制也不可移动。
1 虽然这有点用词不当,因为它并不是那么统一
关于c++ - 错误:'class std::result_of 中没有名为 ‘type’ 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123566/