有没有办法告诉编译器输出向量的类型与操作的返回函数相同,以使这段代码在一般情况下工作?
-- 编辑 -- std::decay<> 在 Barry 的评论之后系统地添加(谢谢!)
我想像(如果你可以使用 C++14)
template <class T, class UnaryOperator>
auto transform_vector(const T& input, UnaryOperator op)
{
std::vector<std::decay_t<decltype(op(*input.begin()))>> output;
std::transform(input.begin(), input.end(),
std::back_inserter(output), op);
return output;
}
对于 C++11 来说有点复杂(而且是多余的),因为你不能简单地使用 auto 作为返回类型
template <class T, class UnaryOperator>
auto transform_vector(const T& input, UnaryOperator op)
-> std::vector<typename std::decay<decltype(op(*input.begin()))>::type>
{
std::vector<typename std::decay<decltype(op(*input.begin()))>::type>
output;
std::transform(input.begin(), input.end(),
std::back_inserter(output), op);
return output;
}
从 C++11 开始工作并避免冗余的另一种方法是通过具有默认值的第三个模板类型参数。
这有点复杂,但我(恕我直言)更有趣,因为允许通过 decltype() 避免自动扣除并强加不同的返回类型。
template <typename T, typename UO,
typename RetV = std::vector<typename std::decay<decltype(std::declval<UO>()
(*std::declval<T>().begin()))>::type>>
RetV transform_vector (T const & input, UO op)
{
RetV output;
std::transform(input.begin(), input.end(),
std::back_inserter(output), op);
return output;
}
这也适用于 C++11。
从 C++14 开始,您可以使用 std::decay_t<T> 而不是 typename std::decay<T>::type 进行简化。