Is it possible to overload a function that can tell a fixed array from a pointer?

前端 未结 6 1838
感动是毒
感动是毒 2020-12-05 14:06

Motivation:

Almost for fun, I am trying to write a function overload that can tell apart whether the argument is a fixed-size array or a pointer.

6条回答
  •  感动是毒
    2020-12-05 14:30

    Here is a simple solution that exploits the fact that in C the value of an array is equal to its address while this is generally not true for a pointer.

    #include 
    
    template 
    bool is_array(const P & p) {
      return &p == reinterpret_cast(p);
    }
    
    int main() {
      int a[] = {1,2,3};
      int * p = a;
    
      std::cout << "a is " << (is_array(a) ? "array" : "pointer") << "\n";
      std::cout << "p is " << (is_array(p) ? "array" : "pointer") << "\n";
      std::cout << "\"hello\" is " << (is_array("hello") ? "array" : "pointer");
    }
    

    Note that while a pointer normally points to a location different from itself, this is not necessarily guaranteed; indeed you can easily fool the code by doing something like this:

    //weird nasty pointer that looks like an array:
    int * z = reinterpret_cast(&z); 
    

    However, since you are coding for fun, this can be a fun, basic, first approach.

提交回复
热议问题