c++ - 为什么字符串作为指针或字符串作为原始数组总是在重载函数中作为指针调用?

标签 c++ string

我有一个函数 check_strconst char*const char(&)[N] 类型重载。

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';
}

然后,我将 arr_01 声明为 const char[]:

const char arr_01[] = "Desmond";

当我调用他们时:

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

第一次调用打印"string as pointer!!",而第二次调用仍然打印"string as pointer!!"

好吧,如果我使用 std::stringstd::string_view,它将失去对它们进行分类的意义。

有没有办法为 arr_01 调用参数类型为 const char(&)[N] 的重载函数,以便打印 "string as array!!" 没有指定非类型模板参数?

最佳答案

使用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

关于c++ - 为什么字符串作为指针或字符串作为原始数组总是在重载函数中作为指针调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68509933/

相关文章:

c++ - 在 Visual Studio 中更改(使用旧的)c++ 版本

c++ - 在 boost graph lib 中,如何在不遍历该顶点的所有出边的情况下获得顶点的特定出边?

C# 字符串拆分 - 索引越界

c - 如何仅从 C 中的 scanf 复制前 n 个字符

c++ - 通过引用传递的函数接受对带有operator()的类的引用

c++ - 如何初始化结构上的 vector vector ?

string - 使用哪种算法将字符串序列排序为 block ,避免以某个元素开头?

string - 如何从 Ansible 中的 lookup() 模块的结果中删除换行符字符 '\n'?

c++ - 在 OS X 中构建和安装 MongoDB C++ 驱动程序

java - Java中如何避免输出回车?