带有迭代器但类型固定的模板函数
Template function with iterators but fixed type
ProcessIndex( int index );
template< typename Iterator >
void ProcessIndexes( Iterator start, Iterator end )
{
while( start!=end )
{
ProcessIndex(*start++);
}
}
我如何强制这个函数只能被特定的,固定的迭代器值类型调用,例如int
(但任何容器类型)?在这种情况下,ProcessIndex()
接受int
作为输入,因此,编译失败的非基本类型,并产生一个警告,例如float
。但是,我希望声明强制执行int
,以便除了int
之外的所有编译都失败。
没有找到"解决方案"在这里或其他地方,尽管良好的努力,是微不足道的(?)。
从c++ 20开始,您可以使用新的概念和requires
关键字来检查迭代器是否指向int
类型:
#include <vector>
void ProcessIndex( int ) {}
template< typename Iterator >
void ProcessIndecies( Iterator start, Iterator end )
requires( std::same_as<std::decay_t<decltype(*start)>, int> )
{
while( start!=end )
{
ProcessIndex(*start++);
}
}
int main() {
std::vector<int> vi;
ProcessIndecies(vi.begin(), vi.end()); //ok
std::vector<float> vf;
//ProcessIndecies(vf.begin(), vf.end()); //fails
}
演示:https://gcc.godbolt.org/z/hba1qh8bz
在c++ 11中,您可以使用enable_if, is_same和decay来完成此操作,如下所示:
#include<iostream>
#include <type_traits>
#include <vector>
void ProcessIndex( int index )
{
//do something here
std::cout<<"Inside ProcessIndex with: "<< index <<std::endl;
}
template< typename Iterator >
auto ProcessIndexes( Iterator start, Iterator end ) -> typename std::enable_if<std::is_same<typename std::decay<decltype(*start)>::type, int>::value>::type
{
std::cout<<"Inside ProcessIndexes"<<std::endl;
while( start!=end )
{
ProcessIndex(*start++);
}
}
int main(){
std::vector<int> vec{1,2,3};
ProcessIndexes(vec.begin(), vec.end()); //WORKS
std::vector<float> vec2;
//ProcessIndexes(vec2.begin(), vec2.end()); //this won't work
}
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 如何创建迭代器函数
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- 使用迭代器的模板类的构造函数
- C++:复制迭代器的构造函数
- 基于函数而不是集合的二分搜索或迭代器?
- 成员函数中的迭代器出现问题
- 使用迭代器的自定义比较器函数
- 专门C++使用指针值类型的通用迭代器的模板函数?
- 从 std::vector 迭代器中执行函数指针
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 如何基于循环迭代器选择函数
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 具有C++迭代器参数的多功能函数
- C++如何获取传递给函数(STL 迭代器)的参数的名称
- C++ 解释重载成员函数迭代器(int i = 0) 的构造"one liner":i(i) { };