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

时间:2017-05-02 12:01:23

标签: c++ c++17

我试图从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

1 个答案:

答案 0 :(得分:2)

std::invoke是一个模板函数。因此,简单地命名模板名称是不明确的 - 你指的是std::invoke<F, Args...>无限集合中的哪一个?

你需要提供一个“调用者”&#39;具体对象。

例如:

#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相同。