使用QVector中的指针和非指针参数的C ++模板

时间:2015-06-08 13:02:28

标签: c++ qt templates pointers

我试图避免两次使用“几乎”相同的代码。我有以下模板函数,它在QVector中搜索提供的值并将索引返回给元素。

template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value)
{
//code here
}

例如,搜索以下类型的向量可以正常工作:QVector<int>,但是我也希望能够搜索该类型的向量 QVector<int*>,所以我写了另一个模板函数。

template<class tVec,class tVal>
int upperBoundIndex(const QVector<tVec*> &vec,int first,int last,tVal value)
{
//similar code here, but the dereferencing
}

这也很好用,但我一直在想,有没有办法可以为两个函数使用相同的代码?因为我几乎将代码从一个函数复制并粘贴到另一个函数中,到目前为止,每当我在一个函数中更改某些函数时,我跳到另一个并应用相同的更改,是否有更优化的解决方案?

P.S。我不是在寻找替代搜索功能,我知道在std命名空间中有搜索功能。我想知道是否有办法优化我的方法。

1 个答案:

答案 0 :(得分:2)

您可以为容器Qvector建模,并使其更通用,例如:

template<class Container>
int upperBoundIndex(const Container &vec,int first,int last,typename Container::value_type value)
{
 // your code
}

但我认为您应该使用std::upper_bound,即使您拥有example to get the index

所以我会使用这种可重复使用的功能:

template<class ForwardIt, class T>
T upperBoundIndex(ForwardIt first, ForwardIt last, const T& value)
{
    return (std::upper_bound (first, last, value) - first);
}

Live example