带有迭代器但类型固定的模板函数

Template function with iterators but fixed type

本文关键字:函数 迭代器 类型      更新时间:2023-10-16
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
}