c++ - 自动与字符串文字

标签 c++ c++11 type-inference auto string-literals

#include <iostream>
#include <typeinfo>

int main()
{
    const char a[] = "hello world";
    const char * p = "hello world";
    auto x = "hello world";

    if (typeid(x) == typeid(a))
        std::cout << "It's an array!\n";

    else if (typeid(x) == typeid(p))
        std::cout << "It's a pointer!\n";   // this is printed

    else
        std::cout << "It's Superman!\n";
}

为什么 x 被推断为指针,而字符串文字实际上是数组?

A narrow string literal has type "array of n const char" [2.14.5 String Literals [lex.string] §8]

最佳答案

auto 特性基于模板参数推导,模板参数推导的行为相同,特别是根据 §14.8.2.1/2(C++11 标准):

  • 如果 P 不是引用类型
    • 如果 A 是数组类型,则使用数组到指针转换产生的指针类型代替 A 进行类型推导

如果希望表达式x的类型为数组类型,只需在auto后添加&即可:

auto& x = "Hello world!";

然后,auto 占位符将被推断为 const char[13]。这也类似于将引用作为参数的函数模板。只是为了避免任何混淆:x 的声明类型将是引用-to-array。

关于c++ - 自动与字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35118761/

相关文章:

c++ - 如何分析基于 C++ STL 的程序以检测 STL 互斥锁?

java - Java 中的泛型用法是什么? X.<Y>方法()

haskell - 查找局部函数的推断类型

c# - 如何以通用方式耦合两个类?

C++ Eigen : recursive functions accepting any matrix class

c++ - 如何在每个共享库中使用自己的静态库拷贝

c++ - 从 CMake 文件生成 Embarcadero 项目文件

c++ - wxWidgets 运行时错误(版本不匹配)

c++ - 是否可以使函数模板对不适当的类型而不是错误执行默认操作?

c++ - lambda 的速度与内联函数