6

Is it even possible to have different functions called for arrays with size known at compile-time than for simple pointers? I have tried all tricks I know of.

template <typename T>
int length(const T* t) {
    return -1;
}

template<typename T, int N>
int length(const T (&)[N]) {
    return N;
}


int main() {
    return length("abc");
}

gcc gives the following error:

source>: In function 'int main()':

<source>:13:24: error: call of overloaded 'length(const char [4])' is ambiguous

     return length("abc");

                        ^

<source>:13:24: note: candidates are:

<source>:2:5: note: int length(const T*) [with T = char]

 int length(const T* t) {

     ^

<source>:7:5: note: int length(const T (&)[N]) [with T = char; int N = 4]

 int length(const T (&)[N]) {

     ^
P.G.
  • 623
  • 6
  • 13
  • The code you posted won’t work? – L. F. Aug 21 '19 at 13:59
  • @MaxLanghof I wouldn't suggest using specializations. Overloads work, they just need SFINAE. function template specializations are second class citizens and don't participate in overload resolution so they should be avoided if possible. – NathanOliver Aug 21 '19 at 14:04

0 Answers0