直接获取基于范围的循环中的元素类型 **例如"using"
get type of element in range based loop **directly** e.g. for "using"
如何获得返回值的类型
我当前使用此操作: - (它可以正常运行)
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 的很整洁,而 Cheers and Hth。-Alf 的s更强大。
遗憾的是我只能接受一个,所以我选择了一个适合我的 small 项目的一个。
最直接的方法:
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。
在一个小的爱好项目中,我当前使用以下代码(它也适用于原始数组,对于没有value_type
TypeDef的容器):
template< class T >
struct Collection_traits_
: Non_instantiable
{
using Collection =
remove_reference_t<T>;
using Iterator =
decltype( begin( declval< ref_<Collection> >() ) );
using Const_iterator =
decltype( begin( declval< ref_<const Collection> >() ) );
using Item =
remove_reference_t< decltype( *declval< Iterator >() ) >;
using Const_item =
remove_reference_t< decltype( *declval< Const_iterator >() ) >;
};
其中
template< class Some_type >
using ref_ = Some_type&;
和remove_reference_t
,begin
和declval
来自标准库。
相关文章:
- 擦除while循环中迭代的元素
- C++:如何循环通过向量中的整数元素
- 对于set上的循环-获取next元素迭代器
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++基于范围的 for 循环和元素副本
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 循环访问还包含未使用元素的字符串数组
- C++用于循环跳过向量的元素?
- 基于相邻元素 c++ 的分段误差范围的循环
- 循环中的变量被设置为下一个数组的元素始终具有相同的内存地址?
- 使用现代C++在 Eigen3 矩阵上使用 for 循环进行元素操作的优雅方式
- 需要帮助编写一个小程序来将循环乘以 n 个元素和 k 个多重性
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 将函数应用于特征矩阵中的所有元素,而无需循环
- 使用 C++ 从每个循环的数组中选择 n 个元素
- 忽略元素的基于范围的 for 循环
- 优先级队列(使用 pairs<int,int> ) 根据 for 循环迭代器的顶级元素
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?