元函数,具有对缺失特征的默认行为以及如何检测随机访问

meta function with default behavior on missing trait and how to detect random access

本文关键字:何检测 访问 随机 检测 函数 默认 特征      更新时间:2023-10-16

以下元函数计算给定类型是否为随机访问迭代器:

    template <class I>
    struct is_random_access
        : boost::is_convertible
        < typename boost::iterator_traversal<I>::type
        , boost::random_access_traversal_tag
        >
    {};

当然,如果I根本不是迭代器,这是行不通的,因为没有定义boost::iterator_traversal<I>

两个独立的问题:

  1. is_random_access不是迭代器时,如何使I返回 false(而不是编译失败)?
  2. 这是检测迭代器是否可随机访问的好方法吗?

对于您的第一个问题,您实际上可以使用维基百科中的SFINEA示例:

template <class... Ts> using void_t = void;
template <class I, class = void>
    struct is_random_access: boost::false_type
    {};
template <class I>
    struct is_random_access<I,void_t<typename std::iterator_traits<I>::iterator_category> >
        : boost::is_convertible
        <typename boost::iterator_traversal<I>::type, boost::random_access_traversal_tag>
    {};

如果输入类型未定义iterator_category类型,它将回退到默认结构,如果已定义,它将使用您的专用化。

对于第二个问题,我不是专家。但是,我的解释与您的解释一致:对于每个具有std::random_access_iterator_tag的迭代器,boost::iterator_traversal<>::type将可转换为boost::random_access_traversal_tag


更新:修复了 int* 未被识别为有效迭代器的问题。I:iteratory_category替换为 std::iterator_traits<I>::iterator_category