简体   繁体   中英

c++ Thread pool std::promise and function type error

I try to write my own version of a Thread pool but have difficulties with lines

            template <typename F, typename...Args>
    auto addWork(F&& f, Args&&... args) -> std::future<decltype (f(args...))>
    {
        using ReturnType = decltype(f(args...));
            //...
            result.set_value(f(args...));
            std::promise<ReturnType> result;
            result.set_value(f(args...));
            return result.get_future();
            //...

Everything seems to work except when f has no parameter or is void type. I don't know how to make "set_value()" work.

Thank for reading.

In case where your ReturnType is void , your std::promise<ReturnType> result variable is a specialisation - std::promise<void> . Its set_value (4) method does not take any arguments.

To fix the issue, you can just use if constexpr to check whether you are dealing with the special case that involves a function returning void . Simply change this:

std::promise<ReturnType> result;
result.set_value(f(args...));
return result.get_future();

to this:

std::promise<ReturnType> result;
if constexpr (std::is_same_v<ReturnType, void>) {
    f(args...);
    result.set_value();
} else {
    result.set_value(f(args...));
}
return result.get_future();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM