问题描述
#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!
";
else if (typeid(x) == typeid(p))
std::cout << "It's a pointer!
"; // this is printed
else
std::cout << "It's Superman!
";
}
当字符串文字实际上是数组时,为什么将 x
推导出为指针?
Why is x
deduced to be a pointer when string literals are actually arrays?
窄字符串文字的类型为n const char
数组"[2.14.5 字符串文字 [lex.string] §8]
推荐答案
auto
特性基于模板参数推导和模板参数推导行为相同,具体根据 §14.8.2.1/2(C++11 标准):
The feature auto
is based on template argument deduction and template argument deduction behaves the same, specifically according to §14.8.2.1/2 (C++11 standard):
- 如果 P 不是引用类型
- 如果 A 是数组类型,则使用数组到指针转换产生的指针类型代替 A 进行类型推导
如果你想让表达式
x
的类型为数组类型,只需在auto
后添加&
:If you want the type of the expression
x
to be an array type, just add&
afterauto
:auto& x = "Hello world!";
然后,
auto
占位符将被推导出为const char[13]
.这也类似于将引用作为参数的函数模板.只是为了避免混淆:x 的声明类型将是reference-to-array.Then, the
auto
placeholder will be deduced to beconst char[13]
. This is also similar to function templates taking a reference as parameter. Just to avoid any confusion: The declared type of x will be reference-to-array.这篇关于带有字符串文字的自动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!