如何定义依赖于参数包转换的函数的返回类型
How to to define return type of a function that depends on parameter pack transformation?
我正在尝试编写一个模板化函数,该函数以可变数量的对作为输入,将一些函数应用于每个"第一个"成员和每个"第二个"成员,并返回结果对。我设法编写了函数本身,但无法自动推断返回类型。如何使用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
相关文章:
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C++:用户定义的显式类型转换函数错误
- 为什么下面带有非常量转换函数的代码没有歧义?
- 为什么转换函数声明不需要至少一个定义类型说明符
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- C++ 通过自定义赋值运算符隐式转换函数参数
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 在C++中自动向下转换函数参数
- static_cast:转换函数模板——它们真的有效吗
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 隐式转换函数的返回对象时是否会影响性能?
- C++不存在合适的转换函数
- 为什么允许 int 和 const int 使用不同的转换函数?
- 使用转换函数直接初始化
- 为什么用户定义的转换函数模板不能有推导的返回类型?
- 为什么我会收到转换函数错误
- 选择用于赋值初始化的转换函数的优先级
- 我收到错误:没有合适的转换函数从 std::basic_istream<char、std::char_traits<char>> 到 char 存在
- 具有转换函数的 lambda,指向具有 C++ 链接的函数的指针
- 使用模板和部分专用化生成类型转换函数