'Is it possible to overload a function that can tell a fixed array from a pointer?
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.
double const d[] = {1.,2.,3.};
double a;
double const* p = &a;
f(d); // call array version
f(p); // call pointer version
I find this particularly difficult because of the well known fact that arrays decay to pointer sooner than later. A naive approach would be to write
void f(double const* c){...}
template<size_t N> void f(double const(&a)[N]){...}
Unfortunately this doesn't work. Because in the best case the compiler determines the array call f(d) above to be ambiguous.
Partial solution:
I tried many things and the closest I could get was the following concrete code. Note also that, in this example code I use char instead of double, but it is very similar at the end.
First, I have to use SFINAE to disable conversions (from array ref to ptr) in the pointer version of the function. Second I had to overload for all possible arrays sizes (manually).
[compilable code]
#include<type_traits> // for enable_if (use boost enable_if in C++98)
#include<iostream>
template<class Char, typename = typename std::enable_if<std::is_same<Char, char>::value>::type>
void f(Char const* dptr){std::cout << "ptr" << std::endl;} // preferred it seems
void f(char const (&darr)[0] ){std::cout << "const arr" << std::endl;}
void f(char const (&darr)[1] ){std::cout << "const arr" << std::endl;}
void f(char const (&darr)[2] ){std::cout << "const arr" << std::endl;}
void f(char const (&darr)[3] ){std::cout << "const arr" << std::endl;}
void f(char const (&darr)[4] ){std::cout << "const arr" << std::endl;}
void f(char const (&darr)[5] ){std::cout << "const arr" << std::endl;}
void f(char const (&darr)[6] ){std::cout << "const arr" << std::endl;} // this is the one called in this particular example
// ad infinitum ...
int main(){
f("hello"); // print ptr, ok because this is the fixed size array
f(std::string("hello").c_str()); // print arr, ok because `c_str()` is a pointer
}
This works, but the problem is that I have to repeat the function for all possible values of N and using template<size_t N> gets me back to square zero, because with the template parameter the two calls get back to equal footing.
In other words, template<size_t N> void f(char const(&a)[N]){std::cout << "const arr" << std::endl;} doesn't help.
Is there any way to generalize the second overload without falling back to an ambiguous call? or is there some other approach?
A C++ or C++1XYZ answer is also welcome.
Two details: 1) I used clang for the experiments above, 2) the actual f will end up being an operator<<, I think know if that will matter for the solution.
Summary of solutions (based on other people's below) and adapted to a the concrete type char of the example. Both seem to depend on making the char const* pointer less obvious for the compiler:
- One weird (portable?), (from the comment of @dyp.) Adding a reference qualifier to the pointer version:
template<class Char, typename = typename std::enable_if<std::is_same<Char, char>::value>::type>
void f(Char const* const& dptr){std::cout << "ptr" << std::endl;}
template<size_t N>
void f(char const (&darr)[N] ){std::cout << "const arr" << std::endl;}
- One elegant (special case from @user657267)
template<class CharConstPtr, typename = typename std::enable_if<std::is_same<CharConstPtr, char const*>::value>::type>
void f(CharConstPtr dptr){std::cout << "ptr" << std::endl;}
template<size_t N>
void f(char const (&darr)[N] ){std::cout << "const arr" << std::endl;}
Solution 1:[1]
You may use the following:
namespace detail
{
template <typename T> struct helper;
template <typename T> struct helper<T*> { void operator() () const {std::cout << "pointer\n";} };
template <typename T, std::size_t N> struct helper<T[N]> { void operator() ()const {std::cout << "array\n";} };
}
template <typename T>
void f(const T& )
{
detail::helper<T>{}();
}
Solution 2:[2]
I like using tag dispatching:
void foo(char const*, std::true_type /*is_pointer*/) {
std::cout << "is pointer\n";
}
template<class T, size_t N>
void foo( T(&)[N], std::false_type /*is_pointer*/) {
std::cout << "is array\n";
}
template<class X>
void foo( X&& x ) {
foo( std::forward<X>(x), std::is_pointer<std::remove_reference_t<X>>{} );
}
Solution 3:[3]
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 <iostream>
template <typename P>
bool is_array(const P & p) {
return &p == reinterpret_cast<const P*>(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<int*>(&z);
However, since you are coding for fun, this can be a fun, basic, first approach.
Solution 4:[4]
In my opinion it is as simple as this:
#include<iostream>
using namespace std;
template<typename T>
void foo(T const* t)
{
cout << "pointer" << endl;
}
template<typename T, size_t n>
void foo(T(&)[n])
{
cout << "array" << endl;
}
int main() {
int a[5] = {0};
int *p = a;
foo(a);
foo(p);
}
I don't get all the complication with std::enable_if and std::true_type and std::is_pointer and magic. If there's anything wrong with my approach please tell me.
Solution 5:[5]
I too was wondering how to get around the compiler complaining about ambiguous overloads and fell across this.
This C++11 solution is similar in form to the dispatching answer but makes use of the variadic SFINAE trick instead (the compiler attempts the array version first). The "decltype" part allows different return types. If the required return type is fixed (e.g. "void" as per the OP) then it is not required.
#include <functional>
#include <iostream>
using std::cout;
using std::endl;
template <typename T> T _thing1(T* x, ...) { cout << "Pointer, x=" << x << endl; return x[0]; }
template <typename T, unsigned N> T _thing1(T (&x)[N], int) { cout << "Array, x=" << x << ", N=" << N << endl; return x[0]; }
template <typename T> auto thing1(T&& x) -> decltype(_thing1(std::forward<T>(x), 0)) { _thing1(std::forward<T>(x), 0); }
int main(int argc, char** argv)
{
const int x0[20] = {101,2,3};
cout << "return=" << thing1(x0) << endl;
int x1[10] = {22};
cout << "return=" << thing1(x1) << endl;
float x2 = 3.141;
cout << "return=" << thing1(&x2) << endl;
const float x3 = 55.1;
cout << "return=" << thing1(&x3) << endl;
}
Example output is:
$ g++ -std=c++11 array_vs_ptr.cpp -o array_vs_ptr && ./array_vs_ptr
Array, x=0x22ca90, N=20
return=101
Array, x=0x22ca60, N=10
return=22
Pointer, x=0x22caec
return=3.141
Pointer, x=0x22cae8
return=55.1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jarod42 |
| Solution 2 | Yakk - Adam Nevraumont |
| Solution 3 | Community |
| Solution 4 | marczellm |
| Solution 5 | alfC |
