如何将模板参数限制为仅指针或随机访问迭代器? [英] How to restrict template parameter to pointer or random access iterator only?
问题描述
是否有一种方法可以将模板函数的参数类型限制为仅指针或随机访问迭代器?
Is there a way to restrict the parameter type of a template function to only pointers or random-access iterators?
说我正在开发仅适用于排序功能与随机可访问的容器。如果用户通过非随机访问迭代器,我正在寻找一种引发编译时错误的方法。
Say I am developing a sorting function which works only with random accessible containers. I am looking for a way to throw a compile-time error if the user passes a non-random-access iterator.
#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
。
I know that to check if a type is a pointer I could use std::is_pointer<Iterator>::value
and to check if the iterator is random access I could use std::is_same<std::random_access_iterator_tag, Iterator::iterator_category>::value
.
第一个问题是两个检查都应在OR中进行或相同的 static_assert()
,否则如果一个匹配,则另一个匹配。
The first problem is that both checks should be OR'd inside the same static_assert()
, otherwise if either one was matched, the other would not.
第二个问题是如果以这种方式调用该函数,则随机访问检查将失败: mySort< int *>(...)
。这显然是由于 int *
没有 :: iterator_category
定义而发生的。
The second problem is that the random access check would fail if the function was to be called called in such a way: mySort<int*>(...)
. This obviously happens since int*
does not have the ::iterator_category
definition.
有人知道如何解决这个问题吗?
我也知道编译器会尝试在非随机访问迭代器中使用算术运算符时自动抛出错误,但是我想通过 static_assert()<显示更全面的错误消息/ code>。
Does anybody have an idea how to solve this?
I also know the compiler would automatically throw errors for the attempt of using arithmetic operators with non-random-access iterators, but I would like to display a more comprehensive error message through static_assert()
.
作为后续问题。在'Iterator'是指针类型的情况下,有没有办法断言它是原始类型(非 struct
/ class
)?
As a follow up question. In the case 'Iterator' is a pointer type, is there a way to assert it is of a primitive type (non 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");
这篇关于如何将模板参数限制为仅指针或随机访问迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!