摘自 http://msdn.microsoft.com/zh-cn/library/dd799546(v=vs.110).aspx
本主题说明了几种方法提供的函数工作 concurrency::call 和 concurrency::transformer 类。
第一个示例说明如何将 lambda 表达式传递给 call 对象。 第二个示例说明如何将函数对象传递给 call 对象。 第三个示例说明如何将类方法绑定到 call 对象。
出于演示的目的,本主题中的每个示例都使用 call 类。 有关使用 transformer 类的示例,请参见如何:在数据管道中使用转换器。
下面的示例说明使用 call 类的常见方法。 此示例将 lambda 函数传递给 call 构造函数。
// call-lambda.cpp // compile with: /EHsc #include <agents.h> #include <iostream> using namespace concurrency; using namespace std; int wmain() { // Stores the result of the computation. single_assignment<int> result; // Pass a lambda function to a call object that computes the square // of its input and then sends the result to the message buffer. call<int> c([&](int n) { send(result, n * n); }); // Send a message to the call object and print the result. send(c, 13); wcout << L"13 squared is " << receive(result) << L'.' << endl; }
该示例产生下面的输出。
13 squared is 169.
下面的示例与上一示例类似,只不过下面的示例将 call 类与函数对象 (functor) 一起使用。
// call-functor.cpp // compile with: /EHsc #include <agents.h> #include <iostream> using namespace concurrency; using namespace std; // Functor class that computes the square of its input. class square { public: explicit square(ITarget<int>& target) : _target(target) { } // Function call operator for the functor class. void operator()(int n) { send(_target, n * n); } private: ITarget<int>& _target; }; int wmain() { // Stores the result of the computation. single_assignment<int> result; // Pass a function object to the call constructor. square s(result); call<int> c(s); // Send a message to the call object and print the result. send(c, 13); wcout << L"13 squared is " << receive(result) << L'.' << endl; }
下面的示例与上一示例类似,只不过它使用 std::bind1st 和 std::mem_fun 函数将 call 对象绑定到类方法。
如果必须将 call 或 transformer 对象绑定到特定的类方法而不是函数调用运算符 operator(),请使用此技术。
// call-method.cpp // compile with: /EHsc #include <agents.h> #include <functional> #include <iostream> using namespace concurrency; using namespace std; // Class that computes the square of its input. class square { public: explicit square(ITarget<int>& target) : _target(target) { } // Method that computes the square of its input. void square_value(int n) { send(_target, n * n); } private: ITarget<int>& _target; }; int wmain() { // Stores the result of the computation. single_assignment<int> result; // Bind a class method to a call object. square s(result); call<int> c(bind1st(mem_fun(&square::square_value), &s)); // Send a message to the call object and print the result. send(c, 13); wcout << L"13 squared is " << receive(result) << L'.' << endl; }
也可以将 bind1st 函数的结果分配给 std::function 对象或使用 auto 关键字,如以下示例所示。
// Assign to a function object. function<void(int)> f1 = bind1st(mem_fun(&square::square_value), &s); call<int> c1(f1); // Alternatively, use the auto keyword to have the compiler deduce the type. auto f2 = bind1st(mem_fun(&square::square_value), &s); call<int> c2(f2);