Home > Software design >  c Thread pool std::promise and function type error
c Thread pool std::promise and function type error

Time:09-26

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.

CodePudding user response:

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();
  • Related