简体   繁体   English

使用谓词模板函数从此处实例化错误

[英]instantiated from here error with a predicate template function

I tried researching this question already, but it seems as though every question dealing with my error has to do with classes and their default constructors whereas my code contains no classes. 我已经尝试过研究这个问题,但似乎每个处理我的错误的问题都与类及其默认构造函数有关,而我的代码不包含任何类。 It's a simple size() function that returns the number of elements in a given array. 它是一个简单的size()函数,它返回给定数组中的元素数。 (I'm aware there is a built in size() function, that's not the point). (我知道有一个内置的size()函数,这不是重点)。

I at first thought that it was upset with my naming my function size() when a size() function already existed so I changed mine to sise() but I still recieve the same error and have no idea how to solve it. 我起初认为当我的函数size()命名时,我已经存在一个size()函数,所以我把它改为sise(),但我仍然收到同样的错误而不知道如何解决它。

Code: 码:

template<class T > int sise(T array[], int count){
  if(array[count+1]== NULL){
    return count+1;
  }
  else{
    return sise(array,count+1);
  }
}

template <class T> int sise(T array[]){
  return sise(array , 0);
  }

int main(){
  int array[] = {1 , 7 , 5, 4, 6 ,2 , 3};
  int len = sise<int>(array);
  std::cout << len << std::endl;
  //print<int>(array);
  //  shakersort<int>(array);
  // print<int>(array);

  return 0;
}

Don't worry about the commented out function calls in main(), as each respective's calls functions have been commented out but the same error of 不要担心main()中注释掉的函数调用,因为每个相应的调用函数都已被注释掉但是同样的错误

Shakersort.cpp: In function ‘int sise(T*, int) [with T = int]’:
Shakersort.cpp:60:24:   instantiated from ‘int sise(T*) [with T = int]’
Shakersort.cpp:77:28:   instantiated from here
Shakersort.cpp:51:3: warning: NULL used in arithmetic [-Wpointer-arith]

is given. 给出。 What is going on? 到底是怎么回事?

The compiler is warning about NULL being compared to an int from the looks of it. 编译器警告将NULL与其外观中的int进行比较。 Not strictly an error (nor is it made an error) but a likely indication of false assumptions being made. 不是严格意义上的错误(也不是错误),而是可能表明存在错误的假设。 One such assumption seems to be that arrays are magically null-terminated: they are not. 一个这样的假设似乎是数组神奇地以空值终止:它们不是。 That is something very specific to string literals and even then the null-terminator is not NULL but rather '\\0' . 这是字符串文字特有的东西,即使这样,null-terminator也不是NULL而是'\\0' You'll either need to pass the size of the array along or you'll need to deduce it using a template, eg: 您需要传递数组的大小,或者您需要使用模板推断它,例如:

template <typename T, int Size>
int sise(T (&array)[Size], int count) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM