gpt4 book ai didi

c++ - std::成员函数的异步调用

转载 作者:可可西里 更新时间:2023-11-01 16:36:27 24 4
gpt4 key购买 nike

考虑以下类:

class Foo
{
private:
void bar(const size_t);
public:
void foo();
};

现在 Foo::foo() 应该启动执行 bar 的线程,所以它是这样实现的:

void Foo:foo()
{
auto handle = std::async(std::launch::async, &Foo::bar, this, 0);
handle.get();
}

这对 g++-4.6.3 完美无缺,但对 g++-4.5.2 无效,错误信息是

include/c++/4.5.2/functional:180:9: Error: must use ».« or »->« to call pointer-to-member function in »std::declval with _Tp = void (Foo::*)(long unsigned int), typename std::add_rvalue_reference<_Tp>::type = void (Foo::&&)(long unsigned int) (...)«, e.g. »(... -> std::declval with _Tp = void (Foo::*)(long unsigned int), typename std::add_rvalue_reference<_Tp>::type = void (Foo::*&&)(long unsigned int)) (...)«

很明显,错误出在旧版本的 g++ 中。可以通过公开该方法并引入以下辅助函数来解决此问题:

void barHelp(Foo* foo, const size_t n)
{
foo->bar(n);
}
void Foo:foo()
{
auto handle = std::async(std::launch::async, barHelp, this, 0);
handle.get();
}

但是,将方法公开并不是最好的设计决策。是否有另一种方法可以更改编译器并将方法保留为私有(private)来解决此问题?

最佳答案

问题似乎是它不能很好地处理成员函数。也许您可以先将成员函数std::bind 传递给您的对象,然后再将其传递给std::async:

auto func = std::bind(&Foo::bar, this, std::placeholders::_1);
auto handle = std::async(std::launch::async, func, 0);

关于c++ - std::成员函数的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14912635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com