【问题标题】:is a string converted to const char* in C++是在 C++ 中转换为 const char* 的字符串
【发布时间】:2025-12-17 13:55:01
【问题描述】:

像“hello”这样的字符串是stringconst char*。 举个例子:

template<typename A>
A s(A a){
    // ...
}

如果我打电话给s("hello"),“hello”会转换成什么?

【问题讨论】:

  • 在 C++ 中,所有文字字符串都是真正的常量字符数组(包括空终止符)。与任何其他数组一样,它可以衰减为指向其第一个元素的指针。它将从不自动转换为std::string

标签: c++ c++17


【解决方案1】:

"hello" 这样的字符串是const char[6]。由于不能按值传递数组,A 将被推导出为const char*

【讨论】:

    【解决方案2】:

    当你在寻找一种类型时,你可以使用这个技巧:

    创建一个没有实现的结构

    template<typename A>
    struct Error;
    

    并使用它:

    template<typename A>
    A s(A a){
        Error<A> error;
        return a;
    }
    
    int main()
    {
        Error<decltype("error")> e; // error: implicit instantiation of undefined template 'Error<char const (&)[6]>'
        s("hello"); // error: implicit instantiation of undefined template 'Error<const char *>'
    }
    

    错误将为您提供您正在寻找的类型。

    多田! "Hello" 类型是 char const [6] 但在 s decuce 类型是 const char *


    学分:

    Effective Modern C++,第 1 章推导类型,第 4 项: 知道如何查看推导类型。

    https://www.oreilly.com/library/view/effective-modern-c/9781491908419/ch01.html

    【讨论】:

    • 除非答案是错误的——"Hello"类型不是const char*,而是const char[6]。您提供的链接明确警告此错误。
    • 已编辑,现在更好了吗?
    • 正确 - 这给出了两个答案。 *.com/questions/30293262/… 解释了为什么 decltype 在第一条错误消息中给出了 (&amp;)