我编写了这个函数,它返回由两个迭代器分隔的范围内的值的平均值:
template<class InputIterator>
typename std::decay<decltype(*std::declval<InputIterator>())>::type mean (InputIterator first, InputIterator last) {
return std::accumulate(first, last, typename std::decay<decltype(*std::declval<InputIterator>())>::type ()) / std::distance(first, last);
}
内部使用和返回的值类型都是从迭代器中推导出来的。由于类型推导的语法非常繁重,我想知道是否有办法避免使用它两次。
我知道我可以添加第二个模板参数并将其默认值设置为值类型,但我不相信,因为有人可能会指定不同的值类型,我想排除这种可能性。
最佳答案
您可以使用 alias templates为 yourType
template<class InIt>
using yourType = typename decay<decltype(*declval<InIt>())>::type;
template<class InIt>
yourType<InIt> mean(InIt first, InIt last)
{
return accumulate(first, last, yourType<InIt>()) / distance(first, last);
}
关于c++ - 在处理模板时,如何避免在函数头和函数体中两次声明相同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23844455/