C++ 与成员函数异步,将另一个meber函数作为参数
我有以下课程:C++ 与成员函数异步,将另一个meber函数作为参数,c++,c++17,member,std-function,stdasync,C++,C++17,Member,Std Function,Stdasync,我有以下课程: class Test { public: void Func1(std::string const& a, std::string const& b, std::function<void(std::vector<double> const&, int)> func); std::vector<double> Func2(std::vector<double> const& v
class Test
{
public:
void Func1(std::string const& a, std::string const& b, std::function<void(std::vector<double> const&, int)> func);
std::vector<double> Func2(std::vector<double> const& v, size_t const i);
};
“fa”和“fb”可以编译,但异步调用“fab”不能编译。我应该如何为Func1调用std::async?
fa
和fb
在实际调用它们之前,不要完全“编译”——函数调用操作符似乎在此之前不会实例化。一旦调用,您就会意识到fb
无效,即fb()
不会编译。一旦您解决了这个问题,async
调用就会工作:)
作为进一步的提示,请注意std::bind
被微妙地破坏了,不建议用于新代码。你最好用兰姆达斯(他们实际上在这里工作!)
捆是怎么断的?像这样:
std::bind(&Test::Func1, &te, a, b, fa)(); // won't compile
但是:
请随意处理。
fa
和fb
在实际调用它们之前,不要完全“编译”——函数调用操作符似乎在此之前不会实例化。一旦调用,您就会意识到fb
无效,即fb()
不会编译。一旦您解决了这个问题,async
调用就会工作:)
作为进一步的提示,请注意std::bind
被微妙地破坏了,不建议用于新代码。你最好用兰姆达斯(他们实际上在这里工作!)
捆是怎么断的?像这样:
std::bind(&Test::Func1, &te, a, b, fa)(); // won't compile
但是:
请随意处理。太好了,它可以根据我的需要工作!请您详细说明一下,或者提供一个链接,关于您的语句“std::bind被微妙地破坏了,不推荐用于新代码”吗?谢谢,你还需要什么证据证明它坏了?它不起作用!这就是你的问题所在。你不会问它是否有用!您可以将给定的参数直接传递给函数,它会接受它,但当您绑定同一个参数时,生成的函子不会编译。这就是
std::bind
被破坏的程度。我们期望std::bind
包装函数调用,因此如果fun(a,b,c,d)
工作,那么您希望std::bind(&fun,a,b,c,d)(
也能工作。正如你所展示的,事实并非如此。不要用它。它坏了:)太好了,它可以按我的需要工作!请您详细说明一下,或者提供一个链接,关于您的语句“std::bind被微妙地破坏了,不推荐用于新代码”吗?谢谢,你还需要什么证据证明它坏了?它不起作用!这就是你的问题所在。你不会问它是否有用!您可以将给定的参数直接传递给函数,它会接受它,但当您绑定同一个参数时,生成的函子不会编译。这就是std::bind
被破坏的程度。我们期望std::bind
包装函数调用,因此如果fun(a,b,c,d)
工作,那么您希望std::bind(&fun,a,b,c,d)(
也能工作。正如你所展示的,事实并非如此。不要用它。它坏了:)
using FnArg = std::function<void(std::vector<double> const&, int)>;
fb = std::bind(&Test::Func1, &te, a, b, FnArg(fa));
fb(); // compiles OK
#include <functional>
#include <future>
#include <string>
#include <vector>
class Test
{
public:
using FnArg = std::function<void(std::vector<double> const&, int)>;
void Func1(std::string const&, std::string const&, FnArg) {}
std::vector<double> Func2(std::vector<double> const&, size_t const) {}
};
int main()
{
Test te;
std::vector<double> vd;
std::string a, b;
auto fa = [&te](const auto &a, auto b){ return te.Func2(a, b); };
auto fb = [=,&te](){ return te.Func1(a, b, fa); };
fa(vd, 1);
fb();
auto fab = std::async(std::launch::async, fb);
fab.wait();
}