直接获取基于范围的循环**中的元素类型**用于“使用”

时间:2017-02-20 05:58:57

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

如何优雅地获取 基于范围的循环的返回值 的类型?

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

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 更健壮 遗憾的是我只能接受一个,所以我选择了适合我的小型项目的那个。

2 个答案:

答案 0 :(得分:1)

最直接的方法:

function ScaleSlider() {
        var refSize = jssor_1_slider.$Elmt.parentNode.clientWidth;
        var refSize1 = jssor_1_slider.$Elmt.parentNode.clientHeight;
        if (refSize) {
            refSize = Math.min(refSize, 830);
            refSize1 = Math.min(refSize1, 617);
            jssor_1_slider.$ScaleWidth(refSize);
            jssor_1_slider.$ScaleHeight(refSize1);
        }
        else {
            window.setTimeout(ScaleSlider, 30);
        }
    }

所有标准库容器都支持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; // 。请参阅http://en.cppreference.com/w/cpp/concept/Container

答案 1 :(得分:1)

在一个小爱好项目中,我目前使用以下代码(它也适用于原始数组,以及没有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来自标准库。