Why was string as pointer or string as raw array always called as pointer in overloaded function?

Viewed 65

I have a function check_str that is overloaded for const char* and const char(&)[N] types.

void check_str(const char*) {
    std::cout << "string as pointer!!" << '\n';
}

template <size_t N>
void check_str(const char(&)[N]) {
    std::cout << "string as array!!" << '\n';
}

Then, I declared arr_01 as const char[]:

const char arr_01[] = "Desmond";

When I call them:

check_str("Desmond");
check_str(arr_01);

The first call prints "string as pointer!!" while the second call still prints "string as pointer!!".

Well, if I use std::string or std::string_view, it will lose the point of classifying them.

Is there a way to call the overloaded function that has the argument type const char(&)[N] for arr_01 in order to print "string as array!!" without specifying the non-type template parameter?

1 Answers

Use std::array:

#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdio>

template <std::size_t sz>
[[nodiscard]] constexpr auto to_array(char const (&cstr)[sz]) noexcept {
  std::array<char, sz> std_arr;
  std::copy_n(cstr, sz, std_arr.data());
  return std_arr;
}

void check_str(char const*) { 
  std::puts("string as pointer!!"); 
}

template <size_t N>
void check_str(std::array<char, N> const&) {
  std::puts("string as array!!");
}

int main() {
  auto constexpr arr = to_array("Desmond");
  check_str("Desmond");
  check_str(arr);
}

Demo

Related