[英]Get the result type of a std::future in a std::function
假设std:::future<T> f
一个实例,我怎样才能从中获取类型T
用于像decltype(f)::result_type
这样的元编程? 如果此std::future<T>
在std::function<void(std::future<T>)> c
,如何获取类型?
std::function<T()>
具有成员类型result_type
和first_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, "");
}
作品。
在foo(callback_t<int>)
,不需要
如何不写 int 而是从回调中派生类型
因为你知道int
是参数,它就在那里。
如果foo
是模板,那也很简单
template <typename T>
void foo (callback_t<T> callback) {
std::packaged_task<T()> task {
[] () {return 42;}
};
task();
callback(task.get_future());
}
如果你真的坚持提取它,你可以写一个trait。
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;
并使用它
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.