Check if a variable type is iterable?

后端 未结 6 1022
失恋的感觉
失恋的感觉 2020-11-29 02:16

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

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 02:56

    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 
    constexpr bool is_iterable() {
        return std::is_base_of::value;
    }
    is_iterable(); // true
    is_iterable(); // false
    

提交回复
热议问题