元函数,具有对缺失特征的默认行为以及如何检测随机访问
meta function with default behavior on missing trait and how to detect random access
以下元函数计算给定类型是否为随机访问迭代器:
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>
。
两个独立的问题:
- 当
is_random_access
不是迭代器时,如何使I
返回 false(而不是编译失败)? - 这是检测迭代器是否可随机访问的好方法吗?
对于您的第一个问题,您实际上可以使用维基百科中的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
。
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- SFINAE - 检测类型 T 是指针、数组还是带有随机访问运算符的容器,以及给定的值类型
- 范围检查检测到的检测代码和超出范围的错误访问
- gcc-如何检测基于指针的内存访问
- 在C++中声明可见性/访问权限的方法有何不同
- 为什么默认情况下使用 [ ] 运算符访问超出范围的矢量元素时,C++检测?
- Qt::如何识别/检测系统是否被Linux中的其他系统远程访问
- 访问检测到的对象/c++内部的像素值
- 在OSX上的Objective C或C++中检测文件夹访问(类似于fs_usage命令)
- 如何检测 C++/COM 中无法访问的代码
- 元函数,具有对缺失特征的默认行为以及如何检测随机访问
- 我是否可以检测成员函数是否存在并且可供C++的朋友访问
- 如何从图像中访问被检测人脸中的人脸像素
- 检测超出范围的访问