有一个快捷方式来decltype [英] Is There a Shortcut to decltype

查看:165
本文介绍了有一个快捷方式来decltype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案中,我写了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:


错误:类型为'int'的类型为'int&'的右值表达式的无效转换

error: invalid cast of an rvalue expression of type 'int' to type 'int&'

很有趣的是,对于 decltype 的参数:

It's interesting that with respect to decltype's argument:


如果对象的名称加括号,作为普通的左值表达式

If the name of an object is parenthesized, it is treated as an ordinary lvalue expression

但是, 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆