自动与字符串文字 [英] auto with 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
一个窄字符串文字的类型为 n
const char
[2.14.5 String Literals [lex.string]§8]
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标准):
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
的类型是一个数组类型, $ c>&之后
:
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类型将是引用 -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.这篇关于自动与字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!