【发布时间】:2015-06-08 13:02:27
【问题描述】:
我试图避免使用“几乎”相同的代码两次。我有以下模板函数,它在 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
}
这也很好用,但我一直在想,有没有办法可以为这两个函数使用相同的代码?因为我几乎将代码从一个函数复制并粘贴到另一个函数,到目前为止,每当我在一个函数中更改某些内容时,我都会直接跳到另一个函数并应用相同的更改,是否有更优化的解决方案?
附言我不是在寻找替代搜索功能,我知道例如在 std 命名空间中有搜索功能。我想知道是否有办法优化我的方法。
【问题讨论】: