我实现了将数据添加到二叉树的一些基本功能。我想练习异步调用,因此我决定将Node添加为async任务。但是,我在调用异步任务的行上发生构建错误。下面是示例代码:使用异步添加二叉树成员无法编译
struct Node
{
static Node *root;
static mutex _mtx;
int _value;
Node *_left;
Node *_right;
Node()
{
_left = nullptr;
_right = nullptr;
}
Node(int value)
{
_left = nullptr;
_right = nullptr;
_value = value;
if (!root) root = this;
else
{
lock_guard<mutex> lck(_mtx);
auto func = bind(&Node::AddNodeAsync, root, ref(*this));
auto ftr = async(launch::async, func); // Error!!!!!!
}
}
void AddNodeAsync(Node *parentNode, Node &nodeToAdd)
{
lock_guard<mutex> lck(_mtx);
AddNode(parentNode, nodeToAdd);
}
void AddNode(Node *parentNode, Node &nodeToAdd)
{
if (nodeToAdd._value < parentNode->_value)
{
if (parentNode->_left == nullptr)
{
parentNode->_left = &nodeToAdd;
}
else
{
AddNode(parentNode->_left, nodeToAdd);
}
}
else if (nodeToAdd._value > parentNode->_value)
{
if (parentNode->_right == nullptr)
{
parentNode->_right = &nodeToAdd;
}
else
{
AddNode(parentNode->_right, nodeToAdd);
}
}
else
{
assert(false);
}
}
};
的错误,我得到:
Severity Code Description Project File Line Suppression State
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)' BinaryTree c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits 1468
我在做什么错?
取而代之的是'bind'呼叫和呼叫'AddNodeAsync'的,它可以全部使用单个[lambda表达式](http://en.cppreference.com/w/cpp/language/lambda)完成。 –
用以下语句替换这两个语句: auto ftr = async(launch :: async,[&](){AddNodeAsync(root,* this);}); 做到了!但为什么第一个版本不起作用? – omegasbk