gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:00 28 4
gpt4 key购买 nike

在这一行中:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com