【问题标题】:Find Item Function Template Giving Me Problems查找给我问题的项目功能模板
【发布时间】:2014-05-05 17:40:46
【问题描述】:

我正在尝试在某个范围内查找项目,因此我对名为“find”的模板化函数进行了多项测试。

template <typename T> T*  find(T *left, T *end, T item);

这是我正在使用的函数原型,它无法与我的第一个测试一起使用:

static void TestFind1(void)
{
  cout << "***** Find1 *****" << endl;
  const int i1[] = {-1, 2, 6, -1, 9, 5, 7, -1, -1, 8, -1};

  int size = sizeof(i1) / sizeof(int);
  const int *end = i1 + size;
  CS170::display(i1, end);
  const int item = 9;
  const int *pos = CS170::find(i1, end, item);
  if (pos != end)
    cout << "Item " << item << " is " << *pos << endl;
  else
    cout << "Item " << item << " was not found" << endl;
}

上面写着@const int *pos“错误:没有函数模板的实例”find”匹配参数列表参数类型是(const int [11], const int *, const int)”

我有第二个原型可以与这个测试一起工作,但它没有完全模板化,所以它失败了第二个测试,它要求一个 int *pos 而不是一个 const int *pos。

第二个原型:

template <typename T> const int* find(T *left, T *end, const int item);

我不太确定我应该如何模板化第一个函数来处理任何情况。

【问题讨论】:

    标签: c++ templates pointers syntax-error function-templates


    【解决方案1】:

    考虑到您尝试将 const int[]const int* 作为参数传递给模板方法调用,并且模板实例化不考虑隐式转换,您的模板函数签名应该是:

    template <typename T> 
    const T* find(const T *left, const T *end, const T& item);
    

    例如:

    template <typename T> 
    const T* find(const T *left, const T *end, const T& item) {
      while (left != end) {
        if (item == *left) {
          return left;
        }
        ++left;
      }
      return end;
    }
    

    或者,您可以更改您的客户端代码以使用非 const int[]int* 参数,并且您的函数模板签名之一应该可以工作。

    但是,您不使用std::find 有什么原因吗?

    【讨论】:

    • 它的任务是制作我们自己的向量库。您的模板有效,但我在 find 下运行了多个测试用例,因此我不能只在每个参数类型之前定义 const 。第二个测试使用除项目之外的所有内容作为 int。
    • 所以请发布您的代码应该通过的所有测试,而不仅仅是一个。
    【解决方案2】:

    您将const int[11] 类型的值作为T* left 参数传递。在普通(非模板)函数中,这是可以的,因为const int[11] 可以隐式转换为const int*,但因为find 是模板,所以不考虑隐式转换。在重载决议期间考虑隐式转换,但模板实例化发生在重载决议之前。

    您可以像这样强制转换:

    const int *pos = CS170::find(static_cast<const int*>(i1), end, item);
    

    或者像这样:

    const int *pos = CS170::find(i1 + 0, end, item);
    

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      相关资源
      最近更新 更多