#include <iostream>
#include <future>
#include <vector>
#include <numeric>
#include <chrono>
#include <functional>

// 计算斐波那契数列的第 n 个数
int fibonacci(int n) {
    if (n <= 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

int main() {
    // 创建一个std::promise对象 用于设置异步任务的返回值
    std::promise<int> prom;

    // 获取std::futre 对象,用于获取异步任务的结果
    std::future<int> fut = prom.get_future();

    // 创建一个新线程来执行异步任务
    std::thread t([n = 10, &prom]() mutable {
       try {
           // 执行异步任务并设置返回值
           int res = fibonacci(n);
           prom.set_value(res);
       } catch(...) {
           // 如果异步任务抛异常了,设置异常信息
           prom.set_exception(std::current_exception());
       }
    });
    // 在新线程中执行异步任务
    t.detach();

    // 等待异步任务完并获取结果
    try {
        int res = fut.get();
        std::cout << res << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }
    return 0;
}

在这个示例代码中,我们首先创建了一个 std::promise 对象,用于设置异步任务的返回值。然后,我们通过调用 prom.get_future() 获取了一个 std::future 对象,用于获取异步任务的结果。接下来,我们创建了一个新线程来执行异步任务,异步任务的返回值通过调用 prom.set_value(result) 来设置。如果异步任务抛出异常,我们通过调用 prom.set_exception(std::current_exception()) 来设置异常信息。最后,我们在主线程中调用 fut.get() 来等待异步任务完成并获取结果。如果异步任务抛出异常,我们可以通过 try-catch 语句来捕获异常并进行处理。