Search code examples
c++templatesc++17class-templatetemplate-argument-deduction

C++17 Using Class Template Argument Deduction guides on a type that holds a function's return value


I designed a object that takes in a function and its parameters and holds the function's return value inside the object to be retrieved later.

My goal here is to create a deduction guide for this object that'll allow me to omit the return type of the function in the object's constructor.

#include <utility>

template <typename Ret> class footure {
  public:
    template <typename Function, typename... Args>
    explicit footure(Function &&fun, Args &&... args) {
        // ...
        value_ = fun(std::forward<Args>(args)...);
        // ...
    }

    Ret get() { return value_; }

  private:
    Ret value_;
};

int add(const int a, const int b) { return a + b; }

int main() {
    auto f = footure<int>(add, 2, 3); // Remove <int>
    auto r = f.get();
}

I've looked up resources such as this PR to try and figure this out, but I could not come up with a solution.


Solution

  • You seem to look for std::invoke_result.

    template <typename Function, typename... Args>
    explicit footure(Function&&, Args&&...) -> footure<std::invoke_result_t<Function&&, Args&&...>>;
    

    Don't forget to add the header <type_traits>.