Check if a variable type is iterable?

后端 未结 6 1012
失恋的感觉
失恋的感觉 2020-11-29 02:16

Is there any way to check if an arbitrary variable type is iterable?

So to check if it has indexed elements or I can actually loop over it\'s children? (Use foreach

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 03:06

    You may create a trait for that:

    namespace detail
    {
        // To allow ADL with custom begin/end
        using std::begin;
        using std::end;
    
        template 
        auto is_iterable_impl(int)
        -> decltype (
            begin(std::declval()) != end(std::declval()), // begin/end and operator !=
            void(), // Handle evil operator ,
            ++std::declval()))&>(), // operator ++
            void(*begin(std::declval())), // operator*
            std::true_type{});
    
        template 
        std::false_type is_iterable_impl(...);
    
    }
    
    template 
    using is_iterable = decltype(detail::is_iterable_impl(0));
    

    Live example.

提交回复
热议问题