Is there a way to have separate template function overloads for pointers and arrays?

  Kiến thức lập trình

First off I would like to draw special emphasis to the C++20 tag as I believe this problem is mutch easier to solve using concepts and the requires statement. Second when I say array here I mean int a[3], I already have a working overload that handles the “normal” std containers including array<int, 3> b (another for map like containers and another for queue like containers). I have a large a function with a large number of overloads to handle different types using the new concepts and requires keyword to have each overload handle as many types as possible. I cannot fine a way to properly distinguish between arrays and pointers. I would like a way that never misclassifies pointers as arrays but if some arrays are classed as pointers it’s not the end of the world (notably if an array has only one element it doesn’t matter at all which it is classed as).

this is close but it doesnt work for this genral case were I do not know what the array is of/pointer is to.

Right now I am using

template<typename T> requires(requires(T& a){1[a];}
                                 && !requires(T& a){a.begin();}
                                 && !is_convertible_v<T, string>
                                 )
         string function(const T& v);

for arrays and

template<typename T> requires(is_pointer_v<T>
                                && !requires(T& a){1[a];}
                                && !is_convertible_v<T, string>
                                )
        string function(T v);

for pointers

This works classes atleast pointers to strings as pointers but everything else I tried was classed as an array.

I would think <type_traits>’s is_array_v<T> would work here; If I add it to my requirements for array and replace !requires(T& a){1[a];} with !is_array_v<T> in my requirements for pointers then pointers work as intended but I get an ambiguous overload error for arrays because it implicitly casts it to a pointer. I was under the impression that implicit casts didn’t work in template instantiation.

New contributor

Smasheded is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT