In the next implementation of static_strlen, why are & & and brackets around str needed?

If I change the type to const char str[Len], I get the following error:

error: no matching function for call to ‘static_strlen(const char [5])’

Is it right what the static_strlenconst char reference array expects? My understanding is that arrays are passed as pointers anyway, so what do elements need to be references? Or is this interpretation completely inappropriate?

#include <iostream>

template <size_t Len>
size_t
static_strlen(const char (&str)[Len])
{
  return Len - 1;
}

int main() {
  std::cout << static_strlen("oyez") << std::endl;
  return 0;
}
+3
source share
2 answers

, Len const chars. , ( , NUL, , -1). , , .

++, , , , . ( ), parens , :

void fn(const char *a[3]); // parameter a is of type const char**, the 3 is ignored.
void fn(const char (*a)[3]; // parameter a is a pointer to an array of 3 const chars.

, . , :

#include <iostream>

void fn(const char (*a)[3]) {
    std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}

void fn2(const char *a[3]) {
    std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}

int main() {
    const char a[3] = {};
    const char **b = 0;
    fn(&a);
    fn2(b);
}

#if 0 
// error: declaration of `a' as array of references
void fn3(const char & a[3]) {
    std::cout << sizeof(a) << "\n" << sizeof(*a) << "\n";
}
#endif
+4

​​, .

static_strlen(const char (&str)[Len])

- , const char Len . . new malloc.

, Len, , .

0

Source: https://habr.com/ru/post/1739533/


All Articles