无法专用化函数模板'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
Code 1:
class thread_obj {
private:
static int instances;
bool run;
static mutex lock;
int threadno;
static map<int, thread> mapOfThreads;
public:
thread_obj():run(true)
{
lock.lock();
threadno = instances++;
thread th(thread_obj::thredfunc, this);
mapOfThreads[threadno] = move(th);
cout << "Thread no is " << threadno << endl;
lock.unlock();
}
static void thredfunc(thread_obj* ptr)
{
while (ptr->run)
{
std::this_thread::sleep_for(100ms);
}
}
void operator()()
{
while (run)
{
std::this_thread::sleep_for(100ms);
}
}
void stop()
{
run = false;
}
static int getTotalthreads()
{
return mapOfThreads.size();
}
~thread_obj()
{
lock.lock();
stop();
if (mapOfThreads[threadno].joinable())
mapOfThreads[threadno].join();
mapOfThreads.erase(threadno);
cout << "Destroyed " << threadno << endl;
lock.unlock();
}
};
int thread_obj::instances = 0;
mutex thread_obj::lock;
map<int, thread> thread_obj::mapOfThreads;
代码 2:
thread_obj():run(true)
{
lock.lock();
threadno = instances++;
thread th(thread_obj(), this);
mapOfThreads[threadno] = move(th);
cout << "Thread no is " << threadno << endl;
lock.unlock();
}
第一个代码工作正常,但是像代码 2 中给出的那样更改构造函数会产生错误。在代码 1 中,构造函数从静态函数创建线程。在代码中,两个构造函数调用非静态运算符((
-
'std::invoke': no matching overloaded function found
-
Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
这背后的原因是什么?(创建此代码是为了处理多个线程。
构造函数中的这一行是无稽之谈:
thread th(thread_obj(), this);
这将构造另一个thread_obj()
对象,然后尝试在新线程中调用它,向其传递this
指针,即thread_obj*
指针。这只有在 operator()
函数采用thread_obj*
参数时才有效,但事实并非如此。
我认为您要做的是在新线程中运行this->operator()()
,因此您将这样做:
thread th(std::ref(*this));
这将创建引用*this
的新线程,然后它将像 (*this)()
一样调用它,这将调用 operator()()
。或者,重命名 operator()
函数以为其指定正确的名称,例如:
void thread_func()
{
while (run)
{
std::this_thread::sleep_for(100ms);
}
}
然后在构造函数中将指向成员函数的指针传递给std::thread
构造函数,this
作为调用该成员函数的对象:
thread th(&thread_obj::thread_func, this);
关于stackoverflow有数百个现有问题,解释了如何在std::thread
中运行成员函数。
相关文章:
- 在noexcept 规范中是否允许使用"this"?
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- 使用 noexcept 运算符 depenendet
- 构建 TensorFlow r1.14 C++文件时缺少文件"tensorflow/core/framework/types.pb.h"
- NOEXCEPT 函数调用运算符的说明符_Not_fn
- 参数包内 noexcept 说明符
- 当 noexcept 函数尝试在 gcc 或 clang 中调用非 noexcept 函数时启用警告
- 为什么使用 std::vector 的代码不能编译,但使用 std::unique_ptr 如果没有 noexcept
- 我如何静态断言static_cast是 noexcept?
- "noexcept-expression 由于对......的调用而计算为'假'"是什么意思?
- 为什么"types may not be defined in parameter types"
- 如何在Arduino程序中解决"invalid operands of types"?
- 如何为C++函数指定 noexcept ?
- 如何知道函数何时抛出以及何时使用noexcept
- 添加noexcept是否会破坏二进制兼容性
- noexcept未通过衰变去除
- 为什么旧的空抛规范被用新的语法"noexcept"重写?
- 在模板中使用 noexcept 运算符
- 错误"invalid types ... for array subscript"是什么意思?
- 在 vs2012 中,lambda 中的 noexcept 如何工作?