Pregunta

I've made is_iterable template as below - which checks that free functions begin/end are available (in the context of ADL) and return proper iterator object. (Which is the requirement for iterable object in ranged-for loop)

#include <utility>
#include <iterator>
#include <type_traits>
#include <vector>

template <typename T>
typename std::add_rvalue_reference<T>::type declval(); // vs2010 does not support std::declval - workaround

template <bool b>
struct error_if_false;

template <>
struct error_if_false<true>
{
};

template<typename U>
struct is_input_iterator
{
    enum {
        value = std::is_base_of<
            std::input_iterator_tag,
            typename std::iterator_traits<U>::iterator_category
        >::value
    };
};

template<typename T>
struct is_iterable
{
    typedef char yes;
    typedef char (&no)[2];

    template<typename U>
    static auto check(U*) -> decltype(
        error_if_false<
            is_input_iterator<decltype(begin(declval<U>()))>::value
        >(),
        error_if_false<
            is_input_iterator<decltype(end(declval<U>()))>::value
        >(),
        error_if_false<
            std::is_same<
                decltype(begin(declval<U>())),
                decltype(end(declval<U>()))
            >::value
        >(),
        yes()
    );

    template<typename>
    static no check(...);

public:
    static const bool value = (sizeof(check<typename std::decay<T>::type>(nullptr)) == sizeof(yes));
};

#include <cstdio>
void write(int a)
{
    printf("%d\n", a);
}

template<typename T>
typename std::enable_if<is_iterable<T>::value>::type write(const T& a)
{
    for (auto i = begin(a), e = end(a); i != e; ++i) {
        write(*i);
    }
}

int main()
{
    write(10);

    std::vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    a.push_back(4);

    write(a);
}

Above code exactly works as intended in vs2010, but not in gcc. Moreover, when I put the some random free function named 'begin', as below, it becomes broken even in vs2010.

int begin(int)
{
}

How can I make the code works? Also, any suggestion that improves the "is_iterable" concept checker would be appreciated.

added: "write" function is just a concept demonstration example - please don't invest your precious time to it. (I know it's not the best code :( ) The part needs some attention is ADL behaviour and "is_iterable" template :)

¿Fue útil?

Solución

After adding std:: to begin/end - your code compiles and runs under gcc-4.6

Improvement suggestion: replace error_if_false with of enable_if

Otros consejos

write(a); should be defined through the operator as Jerry said. Maybe make it more consise so that your code is cleaner.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top