使用async添加二叉树成员无法编译
Adding binary tree member using async fails to compile
我实现了一些向二叉树添加数据的基本功能。我想练习异步调用,因此我决定将Node添加实现为异步任务。但是,我在调用异步任务的行上得到构建错误。下面是示例代码:
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.0vcincludetype_traits 1468
我做错了什么?
您想在哪个Node
上调用AddNodeAsync
?*this
吗?还是root
?这正是问题所在:您没有一个实例来调用AddNodeAsync
!
你想指定哪个实例作为AddNodeAsync
的第一个参数(它是隐式的):
auto func = bind(&Node::AddNodeAsync, this, root, *this);
^^^^
instance to call AddNodeAsync on
另外,最好使用lambdas而不是std::bind
看看void AddNodeAsync(Node *parentNode, Node &nodeToAdd)
,它有两个参数,它也是一个成员函数,它应该得到this
绑定。现在看看你的bind
:
auto func = bind(&Node::AddNodeAsync, root, ref(*this));
所以,bind
接受第一个和第二个参数(第一个是成员函数,第二个是要绑定的this
),并将它们绑定在一起,这取决于你在哪里写
root->AddNodeAsync(ref(*this));
如您所见,缺少一个参数。例如,这个程序编译得很好:
auto func = bind(&Node::AddNodeAsync, root, root, *this);
您忘记了这个参数:
auto func = bind(&Node::AddNodeAsync,this, root, ref(*this));
auto ftr = async(launch::async, func);
无论如何,您可以在一行中使用lambda表达式:
auto ftr = async(launch::async, [this]{ this->AddNodeAsync(root,*this); });
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 访问条件类成员的方法不仅在被调用时才编译
- 为什么下面的模板化类成员函数无法编译?
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 为什么传递非静态成员函数会导致编译错误?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 在C++中,成员函数在编译时可用吗
- 当包含成员函数名为errno和cerrno时,g++7编译错误
- C++模板-基于参数编译成员函数
- 有一个可迭代的容器,其中的成员在编译时是已知的
- 使用成员函数创建std::函数不会编译
- 在VS2017中,我们如何在项目成员之间共享编译设置
- 如何在类成员函数中获得类似printf中的编译警告
- 为什么 std::condition_variable 作为类成员会导致 std::thread 编译错误?
- 如何在 C++11 编译时构建具有递增值的整数成员的结构序列
- 为什么 std::bind 绑定到成员函数时无法编译?
- Std::enable_if有条件地编译成员函数
- c++ 11:条件编译:成员