#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/