Check if a variable type is iterable?

后端 未结 6 1023
失恋的感觉
失恋的感觉 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:59

    Or if (like me) you hate every SFINAE solution being a big block of dummy struct definitions with ::type and ::value nonsense to wade through, here's an example of using a quick and (very) dirty one-liner:

    template <
        class Container,
        typename ValueType = decltype(*std::begin(std::declval()))>
    static void foo(Container& container)
    {
        for (ValueType& item : container)
        {
            ...
        }
    }
    

    The last template argument does multiple things in one step:

    1. Checks to see if the type has a begin() member function, or equivalent.
    2. Checks that the begin() function returns something that has operator*() defined (typical for iterators).
    3. Determines the type that results from de-referencing the iterator, and saves it in case it's useful in your template implementation.

    Limitation: Doesn't double-check that there's a matching end() member function.

    If you want something more robust/thorough/reusable, then go with one of the other excellent proposed solutions instead.

提交回复
热议问题