我想异步运行我的极小极大算法,这样它就不会在等待转弯时卡住用户界面。这是我需要调用的静态方法:
//ChessContext is the current state of the board
//Turn contains fromX, fromY, toX, toY when moving a piece
static Turn getBestTurn(ChessContext cc, int depth);
我已经尝试过这个:
//context is a reference to the game currently played
auto fu = std::async(std::launch::async, ChessContext::getBestTurn, context , 5);
Turn t = fu.get();
它给我一个错误说
boardview.cpp:69:23: error: no matching function for call to 'async'
future:1712:5: note: candidate template ignored: substitution failure [with _Fn = Turn (&)(ChessContext, int), _Args = <ChessContext &, int>]:
no type named 'type' in 'std::result_of<Turn ((ChessContext, int))(ChessContext, int)>'
future:1745:5: note: candidate template ignored: substitution failure [with _Fn = std::launch, _Args = <Turn (&)(ChessContext, int), ChessContext &, int>]:
no type named 'type' in 'std::result_of<std::launch (Turn ()(ChessContext, int), ChessContext, int)>'
我最终希望在单独的线程上的每个可能的回合上运行该算法,或者一次在两个线程上运行该算法,看看它是否可以提高性能。
最少代码:
#include <iostream>
#include <thread>
#include <future>
class Turn
{
};
class ChessContext
{
public:
ChessContext();
ChessContext(ChessContext &cc);
static Turn getBestTurn(ChessContext cc, int depth);
};
int main(){
ChessContext context;
auto fu = std::async(std::launch::async, ChessContext::getBestTurn, context, 5);
}
最佳答案
ChessContext
不可复制。 ChessContext(ChessContext &cc)
不是复制构造函数,您需要 ChessContext(const ChessContext &cc)
。
关于c++ - 如何在C++中异步调用静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59800741/