问题描述
在中,我写了C ++ 17代码:
In this answer I wrote the C++17 code:
cout << accumulate(cbegin(numbers), cend(numbers), decay_t<decltype(numbers[0])>{});
这收到一些关于C ++的类型关联的负面评论,我很遗憾地说我同意:(
This received some negative commentary about the nature of C++'s type association, which I'm sad to say that I agree with :(
decay_t< decltype(numbers [0])> {}
方式获取:
可以保持与数字
'类型的关联,但不能输入30个字符来获取它?
Is it possible to maintain the association with the type of numbers
' elements, but not type like 30 characters to get it?
编辑:
包含 accumulate
或从 numbers [0]中提取类型
的很多答案。 。问题是他们需要读取器导航到辅助位置以读取解决方案,该解决方案不比初始化代码 decay_t {}
。
I've got a lot of answers involving the a wrapper for either accumulate
or for extracting the type from numbers[0]
. The problem being they require the reader to navigate to a secondary location to read a solution that is no less complex than the initialization code decay_t<decltype(numbers[0])>{}
.
唯一的原因是我们不得不这样做: decltype(numbers [0])
是因为返回引用:
The only reason that we have to do more than this: decltype(numbers[0])
Is because the array subscript operator returns a reference:
很有趣的是,对于的参数:
It's interesting that with respect to decltype
's argument:
但是, decltype((numbers [0]))
仍然只是对数字
的元素的引用。所以最后这些答案可能就像我们可以简化这个初始化一样:(
However, decltype((numbers[0]))
is still just a reference to an element of numbers
. So in the end these answers may be as close as we can come to simplifying this initialization :(
推荐答案
个人偏好:舞蹈很烦人和困难的 decay_t
, decltype
和 。
Personal preference: I find the
decay_t
, decltype
and declval
dance pretty annoying and hard to read.
相反,我会使用一个额外的间接级别通过type-trait
value_t< it>
和 init = R {}
Instead, I would use an extra level of indirection through a type-trait
value_t<It>
and zero-initialization through init = R{}
template<class It>
using value_t = typename std::iterator_traits<It>::value_type;
template<class It, class R = value_t<It>>
auto accumulate(It first, It last, R init = R{}) { /* as before */ }
这篇关于有一个快捷方式来decltype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!