C++ 线程时出错,标准::调用:

C++ Error when threading, std::invoke:

本文关键字:标准 调用 出错 线程 C++      更新时间:2023-10-16

好的,所以这些是我的错误。 std::invoke:未找到匹配的重载函数 和 无法专用函数模板"unkown-type std::invoke("可调用 &&,_Types &&...(noexcept(('

我真的需要你们的帮助。我对C++很陌生,所以我希望你能给我一些关于如何做到这一点的例子。不仅解释。

这是我的代码:

#include <iostream>
#include <thread>
#include <stdio.h>
#include <Windows.h>
#include <string>


using namespace std;


void SetColor(int ForgC);
void Navigation();
void Switch(int index);
void UpdateMenu();
const int IWAL = 1;
const int ITRI = 0;
int M_Index = 0;
int Changes = 0;
bool Name1 = false;
bool Name2 = false;
string bools[2] = { "[OFF]", "[ON]" };
void Navigation()
{
for (;;)
{
for (int i = 2; i < 180; i++)
{
if (GetAsyncKeyState(i) & 0x8000)
{
switch (i)
{
case 38:
if (M_Index < 2)
M_Index++;
Changes++;
break;
case 40:
if (M_Index > 0)
M_Index--;
Changes++;
break;
case 37:
Switch(M_Index);
Changes++;
break;
case 39:
Switch(M_Index);
Changes++;
break;
}
Sleep(200);
}
}
}
}
void Switch(int index)
{
if (index == IWAL)
{
Name1 = !Name1;
}
else if (index == ITRI)
{
Name2 = !Name2;
}
}
void UpdateMenu()
{
int temp = -1;
for (;;)
{
if (temp != Changes)
{
temp = Changes;
system("cls");
SetColor(15);
cout << ">> Krizzo's Menu <<" << endl;
cout << "___________________" << endl << endl;
if (M_Index == IWAL)
{
SetColor(10);
cout << " Name1t=t" << bools[Name1] << endl;
}
else
{
SetColor(15);
cout << " Name1t=t" << bools[Name1] << endl;
}
if (M_Index == ITRI)
{
SetColor(10);
cout << " Name2t=t" << bools[Name2] << endl;
}
else
{
SetColor(15);
cout << " Name2t=t" << bools[Name2] << endl;
}
}
}
}
void SetColor(int ForgC)
{
WORD wColor;
//We will need this handle to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
//We use csbi for the wAttributes word.
if (GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
//Mask out all but the background attribute, and add in the foreground color
wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
SetConsoleTextAttribute(hStdOut, wColor);
}
return;
}
int main(int argc, char** argv) {
std::thread t1(Navigation);
std::thread t2(Switch);
std::thread t3(UpdateMenu);
std::thread t4(SetColor);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}

您的SwitchSetColor函数采用参数。必须将此参数传递给thread构造函数。例:

int addOne(int x)
{
return x + 1;
}
int main()
{
std::thread t1(addOne, 5);
t1.join();
}

处理引用参数时,必须将参数包装在std::ref()调用中:

void addOne(int& x)
{
x += 1;
}
int main()
{
int a = 42;
std::thread t1(addOne, std::ref(a));
t1.join();
}

最后,当您想在单独的线程上运行类的成员函数时,您必须传递this指针,因为线程必须知道在哪个实例上调用成员函数。

class X
{
void doSomething()
{
std::thread t1(X::expensiveCalculations, this);
//do something else
t1.join();
}
void expensiveCalculations()
{
}
};
int main()
{
X x;
x.doSomething();
}