簡體   English   中英

C ++ 17結合了std :: async和std :: invoke

[英]C++17 combine std::async and std::invoke

我正在嘗試從std :: async調用內部調用std :: invoke,但是由於某種原因,編譯器不喜歡它。

注意:我知道我可以使用lambda,但是我想在沒有它的情況下使它起作用

這是我的例子。

#include <iostream>
#include <future>
#include <string>
#include <functional>
#include <type_traits>
#include <unistd.h>

template <class Fn, class... Args>
inline std::result_of_t<Fn&&(Args&&...)> runTerminateOnException(Fn&& fn, Args&&... args) {
    try {
        return std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
    } catch (...) {
        std::terminate();
    }
}

struct A {
        static void g(double x, std::string *s) {
            std::cout << "g() : x = " << x << ", *s = " << *s << std::endl;
            usleep(100);
        }

        static void f(double x, std::string *s) {
            std::invoke(g, x, s); // Working
            auto future1 = std::async(std::launch::async, g, x, s); // Working
            auto future2 = std::async(std::launch::async, std::invoke, g, x, s); // Not working
            auto future3 = std::async(std::launch::async, runTerminateOnException, g, x, s); // Not working
        }
};

int main() {
    std::string s = "Hello";
    A::f(10., &s);
    return 0;
}

謝謝您的幫助。

http://coliru.stacked-crooked.com/a/51f8c80b0a05fa0e

std::invoke是模板函數。 因此,簡單地命名模板名稱是模棱兩可的-您是說std::invoke<F, Args...>的無限集合中的哪一個?

您需要提供一個“調用者”具體對象。

例如:

#include <iostream>
#include <future>
#include <string>
#include <functional>
#include <type_traits>
#include <unistd.h>

template <class Fn, class... Args>
inline std::result_of_t<Fn&&(Args&&...)> runTerminateOnException(Fn&& fn, Args&&... args) {
    try {
        return std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
    } catch (...) {
        std::terminate();
    }
}

struct invoker
{
    template<class F, class...Args>
    decltype(auto) operator()(F&& f, Args&&...args) const {
        return std::invoke(f, std::forward<Args>(args)...);
    }
};

struct A {
        static void g(double x, std::string *s) {
            std::cout << "g() : x = " << x << ", *s = " << *s << std::endl;
            usleep(100);
        }

        static void f(double x, std::string *s) {
            std::invoke(g, x, s); // Working
            auto future1 = std::async(std::launch::async, g, x, s); // Working
            auto future2 = std::async(std::launch::async, invoker(), g, x, s); // Working now
//          auto future3 = std::async(std::launch::async, runTerminateOnException, g, x, s); // Not working
        }
};

int main() {
    std::string s = "Hello";
    A::f(10., &s);
    return 0;
}

與模板函數runTerminateOnException相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM