c++ - 当由 ""推导时, `auto` 的确切类型是什么?

标签 c++ c++11 auto c-strings

在这一行中:

auto a = "Hello World";

a确切 类型是什么?我猜是 char[]const char* const 但我不确定。

最佳答案

N4296 2.13.5/8

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

但是由于变量在您的代码中被初始化,它实际上是 const char* ,你可以这样检查。

template<typename> struct TD;

int main()
{
   auto a = "Hello World";
   TD<decltype(a)> _;
}

此处将出现编译错误,您可以在其中看到 TD 的实际类型例如,像这样的 clang

error: implicit instantiation of undefined template 'TD<const char *>'

N4296 7.1.6.4

If the placeholder is the auto type-specifier, the deduced type is determined using the rules for template argument deduction.

template<typename> struct TD;

template<typename T>
void f(T) 
{
   TD<T> _;
}

int main()
{
   auto c = "Hello";
   TD<decltype(c)> _;
   f("Hello");
}

两个类型的实例化对象 TD类型为 TD<const char*> .

N4926 14.8.2.1

Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below.

If P is not a reference type:

If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of A for type deduction

关于c++ - 当由 ""推导时, `auto` 的确切类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089214/

相关文章:

c++ - C++ 中的 C99 样式可变长度数组函数签名

c++ - 并发编译,串行链接

c++ - 我可以告诉我的编译器忽略语句或函数的副作用吗?

C++ : extern variable inside namespace and printf vs cout

C++ shared_ptr use_count for nullptr

c++ - 将 auto 用于 boost::posix_time::time_duration 时出现错误 C2274: 'function-style cast' 的原因是什么?

c++ - C++ 递归中未处理的异常错误

c++ - 不相关类型的动态调度解决方案

c++ - 为什么当我使用 std::string::operator[] 时 auto 变量不会成为引用?

c++ - 编译器如何选择给 auto 赋值?