如何定义依赖于参数包转换的函数的返回类型

How to to define return type of a function that depends on parameter pack transformation?

本文关键字:转换 函数 返回类型 包转换 依赖于 何定义 定义 参数      更新时间:2023-10-16

我正在尝试编写一个模板化函数,该函数以可变数量的对作为输入,将一些函数应用于每个"第一个"成员和每个"第二个"成员,并返回结果对。我设法编写了函数本身,但无法自动推断返回类型。如何使用std::result_of来获得所需的结果?

我的尝试如下:

template<typename Output, typename Func, typename... Inputs>
std::pair<Output, Output> fmap(Func&& f, Inputs&&... inputs)
{
using Out = typename std::result_of<Func(decltype(inputs.first)...)>::type;
return std::pair<Out, Out>(f((inputs.first)...),
f((inputs.second)...));
// Here I would like Out to be the same type as Output
}
int add(int i, int j)
{
return i + j;
}
int main()
{
std::pair<int, int> pair{1, 2};
std::pair<int, int> pair2{4, 5};
auto res = fmap(add, pair, pair2);
// Crashes with template argument deduction failed, couldn't deduce Output
std::cout << res2.first << " " << res2.second << std::endl;
return 0;
}

我想这就是你想要的

template<typename Func, typename... Inputs>
auto fmap(Func&& f, Inputs&&... inputs) 
-> std::pair<typename std::result_of<Func(decltype(inputs.first)...)>::type, typename std::result_of<Func(decltype(inputs.first)...)>::type>
{
using Out = typename std::result_of<Func(decltype(inputs.first)...)>::type;
return std::pair<Out, Out>(f((inputs.first)...),
f((inputs.second)...));
}

https://wandbox.org/permlink/TE6v3vgyOBumHCKV

IMO使用make_pair使其更清洁:

template<typename Func, typename... Inputs>
auto fmap(Func&& f, Inputs&&... inputs) 
-> std::pair<typename std::result_of<Func(decltype(inputs.first)...)>::type, 
typename std::result_of<Func(decltype(inputs.first)...)>::type> // not needed in C++17
{
return std::make_pair(f((inputs.first)...), f((inputs.second)...));
}

https://wandbox.org/permlink/MbNhIfoYvHd2vZ7A
https://wandbox.org/permlink/rM6HUcWINOd60EqZ