我知道这个问题是重复的,但是我找不到其他对我的案例有帮助的问题的答案。我应该提一下,我对C ++还是很陌生,可能犯了许多与线程模块无关的错误。我的目标是使lamda表达式在线程中不断运行,此lambda函数将在每次按下空格键时向值添加一个。然后程序检查该值以查看它是否大于10,如果大于10,则程序退出。问题是每次我尝试构建它时(使用Visual Studio Community 2019),都会出现以下错误:
'std::invoke': no matching overloaded function found
Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
这是我的代码:
#include <thread>
#include <iostream>
#include <Windows.h>
using std::thread;
using std::cout;
using std::endl;
int main()
{
//Value modified by the lambda expression, when it becomes greater than 10,
//the program will wait for the thread to finish and then exit.
int number = 0;
//Value to be checked by the lambda expression everytime the loop repeats,
//if it is false, the loop will break.
bool programRunning = true;
//Lambda expression to update number on screen when spacebar is pressed.
auto update = [](bool& isRunning, int& number) {
while (isRunning)
{
//If space is pressed
if (GetAsyncKeyState(VK_SPACE) != 0)
{
//Add one to the number, this is what the program checks to see if it should exit.
number++;
system("cls");
}
cout << "The current number is " << number << endl;
Sleep(500);
}
};
//Creating thread from lambda function and passing references of programRunning and number.
thread Updater(update, &programRunning, &number);
//Checks if the number modified by the lambda expression is greater than 10,
//if so, the program waits for the thread to finish and then exits.
while (true)
{
if (number > 10)
{
programRunning = false;
Updater.join();
exit(0);
}
else
{
Sleep(500);
}
}
}