gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:17:30 25 4
gpt4 key购买 nike

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

    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_accessI 时返回 false(而不是编译失败)不是迭代器?
  2. 这是检测迭代器是否可随机访问遍历的好方法吗?

最佳答案

对于您的第一个问题,您实际上可以使用 SFINEA example from wikipedia :

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 .

关于c++ - 具有缺失特征默认行为的元函数以及如何检测随机访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com