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

get type of element in range based loop **directly** e.g. for "using"

本文关键字:循环 元素 类型 using 例如 获取 于范围 范围      更新时间:2023-10-16

如何获得返回值的类型 ranged-base base loop extile优雅地?

我当前使用此操作: - (它可以正常运行)

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_tbegindeclval来自标准库。