c++ - 带有 C++ 数组的 decltype

标签 c++

我有一个关于decltype 的问题。对于以下代码:

#include <iostream>
#include <type_traits>

int main()
{
    int a[3];
    std::cout << std::is_same_v<decltype((a)), int(&)[3]> << std::endl;
    std::cout << std::is_same_v<decltype(a + 0), int*> << std::endl;
}

所有输出都是 1。但正如 cppreference 所说:

If the argument is any other expression of type T, and if the value category of expression is lvalue (or pvalue), then decltype yields T& (or T);

我不明白为什么decltype((a))int(&)[3],因为

  1. a 是数组变量,不是左值

  2. (a) 是一个表达式,所以我认为 decltype((a)) 应该返回它的类型,它应该被衰减为 int *,如第二个输出所示。

所以基本上,在使用 decltype 时,我不明白 (a)a + 0 之间的区别。

最佳答案

a is an array variable, which is not a lvalue

a 既是变量名又是表达式。变量本身没有值类别,但当用作表达式时,它是左值。

(a) 是一个表达式,完全等同于表达式a(a) 显然不是变量名。

I think decltype((a)) should return its type

正如您引用的那样,对于表达式,decltype 还通过添加 &&& 或没什么。由于 (a) 是左值,因此添加了 &

should be decayed as int*

数组到指针的衰减并不总是发生。它发生在数组的大多数使用过程中,但不是全部。

特别是,将数组传递给 decltype 时不会发生这种情况。

as the second output shows

在第二种情况下,将 + 应用于数组会强制其衰减为指针。

生成的指针是纯右值,因此报告的类型不是引用。

关于c++ - 带有 C++ 数组的 decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66924236/

相关文章:

c++ - 是否可以保证一个类型的多个type_index实例比较相等?

c++ - 如何正确使用 GMP 来执行此操作?

C++ map<int, vector <int>> 段错误

c++ - Eclipse CDT Luna 未跟踪的 header

c++ - 有没有办法通过类型单独获取 vector 的字节大小?

c++ - 迭代器库的正面和背面提案

c++ - 将 gperftools 与排序一起使用时分析计时器已过期

c++ - SFML 和代码:: block 0xc00000be

c++ - 在单独的可执行文件中调用INSTANTIATE_TEST_CASE_P时,库中的TEST_P测试无法运行

c++ - 使用 C++ 标准库在 Linux 上编译