c++ - 在std::function中获取std::future的结果类型

标签 c++ c++17 future template-meta-programming

假设有一个std:::future<T> f实例,如何为T这样的元编程从其中获取decltype(f)::result_type类型?
以及如果此std::future<T>std::function<void(std::future<T>)> c中,如何获取类型?
例如,std::function<T()>的成员类型为result_typefirst_argument_type(尽管已弃用),但我找不到与std::future类似的任何东西。
我最小化的用例:

#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);
}

最佳答案

以下:

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, "");
}
作品。

关于c++ - 在std::function中获取std::future的结果类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64370052/

相关文章:

java - 无法从返回字符串列表的 Future 对象打印数据

scala - Scala 中的阻塞关键字

c# - C# 中数组/列表的子集迭代器,没有 yield

c++ - 数组和sizeof麻烦编译错误C++

c++ - 我可以确保 RVO 用于重新解释的值吗?

c++17: 一个从未被销毁的临时对象

r - future 的解决方案

c++ - 使用一个 for 循环如何迭代和测试迭代器值?

c++ - CMake if(VARIABLE LESS 22) - 如果 VARIABLE 不存在怎么办?

c++ - std::array<std::vector> 中的大括号省略