SFINAE issue in creating an “is_iterable” trait - is this a gcc bug?

≯℡__Kan透↙ 提交于 2019-12-04 09:29:09

This only works if there's an actual argument to the function which would be a better match than an ellipsis conversion. Remember that parameters with default values for which there's no argument do not participate in overload resolution.

The solution is to add another parameter and pass it an argument:

template<class T> static true_type  is_beg_iterable(int,   // <- for disambiguation
    typename T::const_iterator = C().begin());

template<class T> static false_type is_beg_iterable(...); 

enum { value = sizeof(is_beg_iterable<C>(0)) == sizeof(true_type) }; 
  //                                     ^

Live example.

As of C++17, an idiomatic way to define an is_iterable trait would be:

#include <type_traits>

namespace is_iterable_impl
{
    template<class T>
    using check_specs = std::void_t<
        std::enable_if_t<std::is_same_v<
            decltype(begin(std::declval<T>())), // has begin()
            decltype(end(std::declval<T>()))    // has end()
        >>,                                     // ... begin() and end() are the same type ...
        decltype(*begin(std::declval<T>()))     // ... which can be dereferenced
    >;

    template<class T, class = void>
    struct is_iterable
    : std::false_type
    {};

    template<class T>
    struct is_iterable<T, check_specs<T>>
    : std::true_type
    {};
}

template<class T>
using is_iterable = is_iterable_impl::is_iterable<T>;

template<class T>
constexpr bool is_iterable_v = is_iterable<T>::value;

Live demo.

Following works (at least with gcc 4.9.2):

template<typename C>
struct IsIterable
{
    typedef char true_type;
    typedef long false_type;

    template<class T> static true_type  is_beg_iterable(int,
        typename T::const_iterator = C().begin());
    template<class T> static false_type is_beg_iterable(...);

    enum { value = sizeof(is_beg_iterable<C>(0)) == sizeof(true_type) };
};

Live example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!