如何编写类型特征“ is_container”或“ is_vector”? [英] How to write a type trait `is_container` or `is_vector`?

查看:50
本文介绍了如何编写类型特征“ is_container”或“ is_vector”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能编写一个类型特征,其所有通用STL结构的值都为true(例如, vector set map ,...)?

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

要开始使用,我想写一个类型特质对于 vector 为真,否则为false。我试过了,但是没有编译:

To get started, I'd like to write a type trait that is true for a vector and false otherwise. I tried this, but it doesn't compile:

template<class T, typename Enable = void>
struct is_vector {
  static bool const value = false;
};

template<class T, class U>
struct is_vector<T, typename boost::enable_if<boost::is_same<T, std::vector<U> > >::type> {
  static bool const value = true;
};

错误消息是未在部分专业化中使用的模板参数:U

推荐答案

Look,这是另一个基于SFINAE的用于检测类似STL容器的解决方案:

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

template<typename T, typename _ = void>
struct is_container : std::false_type {};

template<typename... Ts>
struct is_container_helper {};

template<typename T>
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<T>().size()),
                decltype(std::declval<T>().begin()),
                decltype(std::declval<T>().end()),
                decltype(std::declval<T>().cbegin()),
                decltype(std::declval<T>().cend())
                >,
            void
            >
        > : public std::true_type {};

当然,您可能会更改要检查的方法和类型。

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

如果只想检测STL容器(这意味着 std :: vector std :: list 等),您应该执行类似的操作。

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

这篇关于如何编写类型特征“ is_container”或“ is_vector”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆