在处理模板时,如何避免在函数头和函数体中两次声明相同的类型
How to avoid to declare the same type two different times in function header and body when dealing with templates?
我编写了这个函数,它返回两个迭代器分隔的范围内值的平均值:
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);
}
从迭代器推导出在内部使用和返回的值类型。由于类型演绎的语法相当重,我想知道是否有一种方法可以避免使用它两次。
我知道我可以添加第二个模板参数并将其默认值设置为值类型,但我不相信,因为可以指定不同的值类型,我希望排除这种可能性。
您可以使用别名模板为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);
}
现场演示
为避免用户更改默认类型,您可以添加可变模板
template <typename InputIterator,
typename...,
typename Type = typename std::decay<decltype(*std::declval<InputIterator>())>::type
>
Type mean (InputIterator first, InputIterator last) {
return std::accumulate(first, last, Type()) / std::distance(first, last);
}
,甚至更安全,以避免向mean
提供更多的模板参数。
template <typename InputIterator,
typename...DummyTs,
typename Type = typename std::decay<decltype(*std::declval<InputIterator>())>::type,
typename = typename std::enable_if<sizeof...(DummyTs) == 0>::type
>
Type mean (InputIterator first, InputIterator last) {
return std::accumulate(first, last, Type()) / std::distance(first, last);
}
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- C++析构函数调用两次,堆栈分配的复合对象
- 为什么参数在构造 std::thread 时移动两次
- 析构函数在 lambda 捕获说明符中声明的类实例上运行两次
- 为什么对isnan的呼吁并不含糊?a.k.a.关键字使用引入两次相似的函数声明
- 在静态数组声明中使用了两次C++常量
- 两次声明纯虚拟函数(在层次结构中的两个类中)是否完全合法
- 为什么Microsoft在他们的 winnt.h 文件中两次 typedef 声明什么构成 "double" ?
- 在处理模板时,如何避免在函数头和函数体中两次声明相同的类型
- 为什么静态变量需要在c++中声明两次?
- 声明同一个非成员函数两次
- 类构造函数声明了两次