c++ - **直接**获取基于范围的循环中的元素类型,例如对于 "using"

标签 c++ c++11 data-structures foreach iterator

如何优雅地获取返回值 ranged-base 循环的类型?

我目前使用这个:-(它工作正常)

using Encapsulator= std::vector<int>;  //<-- any datastructure
using ReturnType = decltype(std::declval<Encapsulator>().begin().operator*());
//^ ReturnType is "int&"

目标:ReturnType 是一种符合单词auto 的类型:-

for(auto returnType : an-instance-of-Encapsulator ){}

但是,我觉得我上面的代码一点都不优雅。
看久了觉得头晕。

问题

标准库/语法中有没有像这样优雅地工作的东西?

using ReturnType = std::rangedBasedLoopType<Encapsulator>;    

我想知道我是否应该自己编写 rangedBasedLoopType 代码,但我正在努力避免重新发明轮子。

我重新发明轮子

我的坏...我无法抗拒。此代码工作正常。

template<class Collection> using GetReturn =
    decltype(std::declval<Collection>().begin().operator*());
using ReturnType = GetReturn<Encapsulator>;    

编辑(接受答案后):

对我来说,这两个答案都很好。非常感谢!
R Sahu 很整洁,而干杯和hth。 - Alf 的更健壮。
很遗憾我只能接受一个,所以我选择了适合我的项目的那个。

最佳答案

最直接的方法:

using Encapsulator= std::vector<int>;
using ItemType = Encapsulator::value_type;   //
using ValueType = Encapsulator::value_type;  // Use on of these three
using ReturnType = Encapsulator::value_type; //

所有标准库容器都支持value_type。参见 http://en.cppreference.com/w/cpp/concept/Container .

关于c++ - **直接**获取基于范围的循环中的元素类型,例如对于 "using",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337435/

相关文章:

c++ - 使用 c++ typedef/使用类型别名

c++ - 这种类型的内存管理有用例吗?

c++ - Qt : Avoid Rebuilding Applications incase strings change

c++ - vector 迭代器不可取消引用(尝试手动反转 vector )

c++ - 在 Qt 中确定 TCP 套接字上的数据类型

C链表指针理解

data-structures - 如何最好地表示 3D 欧几里得空间中的网格图?

c++ - 为什么 gcc 会用 _mm512_dpbusds_epi32 添加额外的 vmovdqa64 指令?

c++ - 从其他类访问非类型模板参数的最佳方法是什么?

c++ - 比较 unordered_map 与 unordered_set