有没有办法将模板函数的参数类型限制为仅指针或随机访问迭代器?
假设我正在开发一个排序功能,该功能仅适用于可随机访问的容器。我正在寻找一种在用户传递非随机访问迭代器时抛出编译时错误的方法。
#include <type_traits>
#include <iterator>
template <class Iterator> void mySort(Iterator begin, Iterator end){
/*The below condition must be true if the 'Iterator' type is a pointer
or if it is of Category random_access_iterator_tag. How to make such check?*/
static_assert(some condition, "The mySort() function only accepts random access iterators or raw pointers to an array.\n");
for (Iterator it = begin; it != end; ++it){
/*Some kind of sorting is performed here, which
uses arithmetic operators + and - in the iterator type. */
}
}
我知道要检查类型是否是指针,我可以使用std::is_pointer<Iterator>::value
并检查迭代器是否是随机访问我可以使用std::is_same<std::random_access_iterator_tag, Iterator::iterator_category>::value
.
第一个问题是两个检查应该在同一个检查中进行“或”运算static_assert()
,否则如果其中一个匹配,另一个就不会。
第二个问题是,如果以这种方式调用该函数,随机访问检查将会失败:mySort<int*>(...)
。这显然是从那时起发生的int*
没有::iterator_category
定义。
有人知道如何解决这个问题吗?
我还知道编译器会在尝试将算术运算符与非随机访问迭代器一起使用时自动抛出错误,但我想通过显示更全面的错误消息static_assert()
.
作为后续问题。如果“Iterator”是指针类型,有没有办法断言它是原始类型(非struct
/class
)?
先感谢您。