我有一个可调用类型的元组。
std::tuple<std::function<int(int)>, std::function<std::string(double)>> funcs;
我想创建另一个具有每个callable结果类型的元组。例如,funcs
包含int->int
和double->std::string
如何创建依赖于results
中每个元素的funcs
元组,它们可能如下所示。
std::tuple<int, std::string> results;
答案 0 :(得分:1)
#include <tuple>
#include <functional>
#include <string>
// takes an arbitrary tuple of std::functions and creates a
// tuple of the return types of those std::functions
template<class T, class... Types>
struct TupleHandler;
// handles the recursive inheritance base case when all the
// elements of the tuple have been processed
template<class... Types>
struct TupleHandler<std::tuple<>, Types...> {
using ReturnTypeTuple = std::tuple<Types...>;
};
// Strips off the first std::function in the tuple, determines
// its return type and passes the remaining parts on to have the next element
// processed
template<class Return, class... Rest, class... Tail, class... Types>
struct TupleHandler<std::tuple<std::function<Return(Rest...)>, Tail...>, Types...> : TupleHandler<std::tuple<Tail...>, Types..., Return> {
using ReturnTypeTuple = typename TupleHandler<std::tuple<Tail...>, Types..., Return>::ReturnTypeTuple;
};
int main()
{
std::tuple<std::function<int(int)>, std::function<std::string(double)>> funcs;
// Of course for this simple use case you could have just used std::make_tuple, but it still demonstrates the solution
TupleHandler<decltype(funcs)>::ReturnTypeTuple return_value_tuple(std::get<0>(funcs)(1), std::get<1>(funcs)(4.4));
// added per comment
auto x = [](auto funcs){ typename TupleHandler<decltype(funcs)>::ReturnTypeTuple results; };
}
答案 1 :(得分:1)
非递归方式:
JAVA_HOME=C:\jdk1.5.0_06
PATH=%JAVA_HOME%\bin;%PATH%
CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar
答案 2 :(得分:1)
std::function
有一个名为result_type
的成员typedef。只需使用它。
template<class... Funcs>
auto tuple_function_ret_impl(std::tuple<Funcs...>)
-> std::tuple<typename Funcs::result_type ...>;
template<class Tuple>
using tuple_function_ret = decltype(tuple_function_ret_impl(Tuple()));
Demo:
using func_tuple = std::tuple<std::function<int(int)>,
std::function<std::string(double)>>;
using ret_tuple = tuple_function_ret<func_tuple>;
using ret_tuple = std::tuple<int, std::string>; // OK