How to write a trait which checks whether a type is iterable
c++, iterable, templates, type-traits
Solution
It depends on what you mean by "iterable". It is a loose concept in C++ since you could implement iterators in many different ways.
If by `foreach` you're referring to C++11's range-based for loops, the type needs `begin()` and `end()` methods to be defined and to return iterators that respond to `operator!=`, `operator++` and `operator*`.
If you mean Boost's BOOST_FOREACH helper, then see BOOST_FOREACH Extensibility.
If in your design you have a common interface that all iterable containers inherit from, then you could use C++11's std::is_base_of:
struct A : IterableInterface {}
struct B {}
template <typename T>
constexpr bool is_iterable() {
return std::is_base_of<IterableInterface, T>::value;
}
is_iterable<A>(); // true
is_iterable<B>(); // false
Problem
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++.