c ++中是否有一个方法/函数,其后的常量参数基于第一个? [关闭]

问题描述 投票:1回答:1

常量参数列表似乎是错误的。我想使用基于第一个的最后一个参数

#include<iostream>
#include<vector>
using namespace std;        

template<class T>
int ExistIndex(const vector<T> v, T obj, int start = 0, int end = v.size() - 1)
{
    //The last parameter is the problem 
    //Finds the index where obj exists in the vector. If it does not 
    // -1 is returned. does not check for bounds
    for (int i = start; i <= end; i++)
    {   
        //Finding the object
        if (v[i] == obj) return i;
    }
    return -1;
}

int main()
{
      //Executing
      vector<int> v1 = {1, 2, 3, 4}
      int l = ExistIndex(v1, 3);// Although this compiles

      cout << endl;
      system("pause");
      return 0;
}
c++ function templates parameter-passing
1个回答
2
投票

您写的是does not compile for me。我看到:

prog.cpp:6:67: error: local variable ‘v’ may not appear in this context
 int ExistIndex(const vector<T> v, T obj, int start = 0, int end = v.size() - 1)
                                                                   ^

但是,要实现这一点,我将使用较少的参数来重载该函数,并让该函数调用您的“真实”函数(这始终是默认参数在后台执行的操作:]

template<class T>
int ExistIndex(const vector<T> v, T obj, int start = 0)                                                                                                
{
    return ExistIndex(v, obj, start, v.size() - 1);
}

0
投票

查看此:why can't default argument depend on non-default argument?(我应该发表评论,因为这不是我的回答,但我没有足够的声誉来做到这一点)

© www.soinside.com 2019 - 2024. All rights reserved.