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
cpprefence has an example answering your question. It is using SFINAE, here is a slightly modified version of that example (in case the content of that link gets changed over time):
template
struct is_iterable : std::false_type {};
// this gets used only when we can call std::begin() and std::end() on that type
template
struct is_iterable())),
decltype(std::end(std::declval()))
>
> : std::true_type {};
// Here is a helper:
template
constexpr bool is_iterable_v = is_iterable::value;
Now, this is how it can be used
std::cout << std::boolalpha;
std::cout << is_iterable_v> << '\n';
std::cout << is_iterable_v> << '\n';
std::cout << is_iterable_v << '\n';
struct A;
std::cout << is_iterable_v << '\n';
Output:
true
true
false
false
Having said that, all it checks is, the declaration of begin() const and end() const, so accordingly, even following is verified as an iterable:
struct Container
{
void begin() const;
void end() const;
};
std::cout << is_iterable_v << '\n'; // prints true
You can see these pieces together here