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.

Answer

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