How to write a type trait `is_container` or `is_vector`?

前端 未结 10 1348
不知归路
不知归路 2020-11-27 14:11

Is it possible to write a type trait whose value is true for all common STL structures (e.g., vector, set, map, ...)?

To get s

10条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 14:53

    Look, another SFINAE-based solution for detecting STL-like containers:

    template
    struct is_container : std::false_type {};
    
    template
    struct is_container_helper {};
    
    template
    struct is_container<
            T,
            std::conditional_t<
                false,
                is_container_helper<
                    typename T::value_type,
                    typename T::size_type,
                    typename T::allocator_type,
                    typename T::iterator,
                    typename T::const_iterator,
                    decltype(std::declval().size()),
                    decltype(std::declval().begin()),
                    decltype(std::declval().end()),
                    decltype(std::declval().cbegin()),
                    decltype(std::declval().cend())
                    >,
                void
                >
            > : public std::true_type {};
    

    Of course, you might change methods and types to be checked.

    If you want to detect only STL containers (it means std::vector, std::list, etc) you should do something like this.

提交回复
热议问题