在this answer我写了 C++17 代码:
cout << accumulate(cbegin(numbers), cend(numbers), decay_t<decltype(numbers[0])>{});
这收到了一些关于 C++ 类型关联性质的负面评论,我很遗憾地说我同意 :(
decay_t<decltype(numbers[0])>{}
是一种非常复杂的方法来获得:
Zero-initialized type of an element of
numbers
是否可以保持与 numbers
类型的关联? ' 元素,而不是键入 30 个字符来获取它?
编辑:
我有很多答案都涉及 accumulate
的包装器或者从 numbers[0]
中提取类型.问题是它们要求读者导航到次要位置以阅读不比初始化代码复杂的解决方案 decay_t<decltype(numbers[0])>{}
.
我们必须做更多事情的唯一原因:decltype(numbers[0])
是因为array subscript operator返回一个引用:
error: invalid cast of an rvalue expression of type 'int' to type 'int&'
有趣的是,关于 decltype
的论据:
If the name of an object is parenthesized, it is treated as an ordinary lvalue expression
然而,decltype((numbers[0]))
仍然只是对 numbers
元素的引用.所以最后这些答案可能与我们可以简化这个初始化的结果一样接近:(
最佳答案
虽然我总是选择按照@Barry 编写辅助函数, 如果 numbers 是一个标准容器,它会导出类型 value_type,这样你可以节省一点复杂性:
cout << accumulate(cbegin(numbers), cend(numbers), decltype(numbers)::value_type());
更进一步,我们可以定义这个模板函数:
template<class Container, class ElementType = typename Container::value_type>
constexpr auto element_of(const Container&, ElementType v = 0)
{
return v;
}
这给了我们这个:
cout << accumulate(cbegin(numbers), cend(numbers), element_of(numbers, 0));
关于c++ - 是否有 decltype 的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36268132/