Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable type is iterable?

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++.

like image 329
Roy Nieterau Avatar asked Dec 11 '12 23:12

Roy Nieterau


People also ask

How do you know if a variable is iterable?

As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn't. This is more accurate than using isinstance(x, abc. Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.

How do you check if an array is iterable?

Check If a JavaScript Value is Iterable In order to be iterable, an object must implement the @@iterator method. You can also reference the @@iterator method using the Symbol. iterator constant. It points JavaScript to the same method.

How can you tell if an object is an iterator?

An object is Iterable if it can give you Iterator . It does so when you use iter() on it. An object is Iterator if you can use next() to sequentially browse through its elements. For example, map() returns Iterator and list is Iterable .


1 Answers

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.

like image 125
Jarod42 Avatar answered Oct 30 '22 18:10

Jarod42