有没有办法将模板函数的参数类型限制为仅指针或随机访问迭代器?
假设我正在开发一个仅适用于随机可访问容器的排序函数。我正在寻找一种在用户传递非随机访问迭代器时抛出编译时错误的方法。
#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()
中进行 OR' , 否则如果其中一个被匹配,另一个就不会。
第二个问题是,如果以这种方式调用函数,随机访问检查将失败:mySort<int*>(...)
.这显然发生在 int*
没有 ::iterator_category
定义。
有人知道如何解决这个问题吗?
我也知道编译器会在尝试将算术运算符与非随机访问迭代器一起使用时自动抛出错误,但我想通过 static_assert()
显示更全面的错误消息。 .
作为后续问题。如果“迭代器”是指针类型,有没有办法断言它是原始类型(非 struct
/class
)?
提前谢谢你。
最佳答案
使用迭代器特征:
static_assert(
std::is_same<std::random_access_iterator_tag,
typename std::iterator_traits<Iterator>::iterator_category>::value,
"The mySort() function only accepts random access iterators or raw pointers to an array.\n");
关于c++ - 如何将模板参数限制为仅指针或随机访问迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23665053/