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.>
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.