Check if a variable type is iterable?

Roy Nieterau picture Roy Nieterau · Dec 12, 2012 · Viewed 10k times · Source

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 for example?)

Is it possible to create a universal template for that?

I've found techniques for other programming languages while searching for it. Yet still have to find out how to do this in C++.

Answer

Jarod42 picture Jarod42 · Apr 14, 2015

You may create a trait for that:

namespace detail
{
    // To allow ADL with custom begin/end
    using std::begin;
    using std::end;

    template <typename T>
    auto is_iterable_impl(int)
    -> decltype (
        begin(std::declval<T&>()) != end(std::declval<T&>()), // begin/end and operator !=
        void(), // Handle evil operator ,
        ++std::declval<decltype(begin(std::declval<T&>()))&>(), // operator ++
        void(*begin(std::declval<T&>())), // operator*
        std::true_type{});

    template <typename T>
    std::false_type is_iterable_impl(...);

}

template <typename T>
using is_iterable = decltype(detail::is_iterable_impl<T>(0));

Live example.