在Casablanca工作者线程中运行lambda函数

时间:2019-05-28 07:10:02

标签: c++14 casablanca cpprest-sdk

如何使用Casablanca pplx::task将参数传递给lambda函数?

没有卡萨布兰卡:

auto f = [](int x) {
    cout <<"Hello "<<x<<endl;
    return 5;
};
f(4);

与卡萨布兰卡一起,

auto g = [](/*argument x*/ ??) {
    cout <<"Hello "<<x<<endl;
    return 5;
};


pplx::task<int>(f(/*pass argument ?? */))
.then([](pplx::task<int> prevTask)
{
    int res;
    try {
        res = prevTask.get();
    }catch(const std::exception &e) {
        cout << e.what() << endl;
    }
}).wait();

我尝试传递简单的intpplx::task<int>(g(3)),但无法编译。

代码:

#include <cpprest/asyncrt_utils.h>
using namespace std;
using namespace utility;
int main() {
    auto f = [](int x) {
        std::cout <<"Hello "<<x<<std::endl;
        return 5;
    };
    f(4);

    #if 0 // does not work
    auto g = [](int x) {
        cout <<"Hello "<<x<<endl;
        return 5;
    };
    pplx::task<int>(g(3))
    .then([](pplx::task<int> prevTask)
    {
        int res;
        try {
            res = prevTask.get();
        }catch(const std::exception &e) {
            cout << e.what() << endl;
        }
    }).wait();
    #endif
}

CMakeLists.txt:

cmake_minimum_required (VERSION 3.5)
set(CMAKE_BUILD_TYPE Debug)
project(TEST)

message(STATUS "Compiling TestFile : ${PROJECT_NAME}")
set (CMAKE_CXX_STANDARD 17)
message(STATUS "Project Directory: ${PROJECT_SOURCE_DIR}")

set (CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)

add_executable(${PROJECT_NAME} test.cpp)

set(REST_LIBRARIES "-lcpprest")
set(CMAKE_CXX_FLAGS "-std=c++17 -Wall -g -fsanitize=address")

target_link_libraries(${PROJECT_NAME} ${REST_LIBRARIES})

在Ubuntu libcpprest-dev

中的必需安装

更新:它使用以下语法:

#include "cpprest/asyncrt_utils.h"
using namespace std;
using namespace utility;
int main() {

    auto g = [](std::string x) {
        cout<<x;
        return std::string(" World!");
    };

    pplx::task_from_result<std::string>("Hello")
    .then([g](std::string x)
    {   
        auto ret = g(x);
        return ret;
    })
    .then([](pplx::task<std::string> prevTask)
    {
        cout << prevTask.get() <<endl;

    }).wait();
}

是否需要使用task_from_result

0 个答案:

没有答案