简体   繁体   English

C ++ 17使用类模板参数在一个包含函数返回值的类型上的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. 我已经查找了这个PR这样的资源来试图解决这个问题,但我无法想出一个解决方案。

You seem to look for std::invoke_result . 你似乎在寻找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> . 不要忘记添加标题<type_traits>

The class must know about the Function and Args at compile time. 该类必须在编译时了解FunctionArgs Only then can you deduce the type of _value like so: 只有这样才能推断出_value的类型, _value所示:

#include <utility>
#include <type_traits>

template <typename Function, typename... Args> class footure {
  public:

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

    auto get() { return value_; }


  private:
     typename std::result_of<Function&(Args...)>::type value_;
};

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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