假设有一个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, "");
}
作品。
关于c++ - 在std::function中获取std::future的结果类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64370052/