首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取std::函数中std::future的结果类型

问获取std::函数中std::future的结果类型
EN

Stack Overflow用户
提问于 2020-10-15 18:56:07
回答 2查看 102关注 0票数 1

假设有一个std:::future<T> f实例,我如何才能为像decltype(f)::result_type这样的元编程获取类型T呢?以及如果此std::future<T>位于std::function<void(std::future<T>)> c中,如何获取类型

例如,std::function<T()>有成员类型result_type和first_argument_type (虽然已弃用),但我找不到与std::future类似的成员类型。

我的最小化用例:

代码语言:javascript
复制
#include <future>
#include <functional>

#include <iostream>

template<typename T>
using callback_t = std::function<void(std::future<T>)>;

void foo (callback_t<int> callback) {
    std::packaged_task<int/*How to not write int but derive the type from callback*/()> task {
        [] () {return 42;}
    };

    task();
    callback(task.get_future());
}

int main()
{
    callback_t<int> c {[] (auto i) {
        std::cout << i.get() << "\n";
    }};
    foo (c);
}
EN

回答 2

Stack Overflow用户

发布于 2020-10-15 19:14:12

以下内容:

代码语言:javascript
复制
template<class T> struct get_first_argument_type {};
template<class R, class Arg>
struct get_first_argument_type<std::function<R(Arg)>> {
    using argument_type = Arg;
};

template<typename T>
void foo(callback_t<T> callback) {
    using the_future = typename get_first_argument_type<callback_t<T>>::argument_type;
    // https://stackoverflow.com/questions/26435084/how-to-get-the-return-type-of-a-member-function-from-within-a-class
    using your_type = typename std::result_of<decltype(&the_future::get)(the_future)>::type;
    static_assert(std::is_same<your_type, int>::value, "");
}

很管用。

票数 3
EN

Stack Overflow用户

发布于 2020-10-15 21:10:13

在foo(callback_t<int>)中,不需要

如何不编写int而是从回调派生类型

因为您知道int是参数,所以它就在那里。

如果foo是一个模板,那么它也会很简单

代码语言:javascript
复制
template <typename T>
void foo (callback_t<T> callback) {
    std::packaged_task<T()> task {
        [] () {return 42;}
    };

    task();
    callback(task.get_future());
}

如果你真的坚持要提取它,你可以写一个特征。

代码语言:javascript
复制
template <typename>
struct callback_arg;

template <typename T>
struct callback_arg<callback_t<T>> { using type = T; };

template <typename T>
using callback_arg_t = typename callback_arg<T>::type;

并像这样使用它

代码语言:javascript
复制
using int_callback = std::function<void(std::future<int>)>;

void foo (int_callback callback) {
    std::packaged_task<callback_arg_t<int_callback>()> task {
        [] () {return 42;}
    };

    task();
    callback(task.get_future());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64370052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档