我正在尝试编写一个模板化的函数,该函数以可变对的输入为输入,对每个“第一个”成员和每个“第二个”成员应用某个函数,并返回结果对。我设法编写了函数本身,但无法获得自动推断的返回类型。如何使用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)...));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句