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++.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With