gpt4 book ai didi

c++ - 对 is_array 模板类的评估感到困惑

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:49 24 4
gpt4 key购买 nike

考虑以下程序(参见现场演示 here.)

#include <iostream>
#include <type_traits>
int main()
{
struct T{ virtual void foo()=0;};
std::cout<<std::boolalpha;
std::cout<<std::is_array<int[3]>::value<<'\n';
std::cout<<std::is_array<T>::value<<'\n';
std::cout<<std::is_array<T1[2]>::value<<'\n';
std::cout<<std::is_array<T[3]>::value<<'\n'; // why uncommenting this line causes compile time error?
}

我知道不可能创建抽象类的对象。这里 T 是抽象的,所以不可能创建结构 T 的对象。但是请考虑以下语句

std::cout<<std::is_array<T[3]>::value<<'\n';

为什么它给我一个错误?该语句仅检查给定类型是否为数组。这是否意味着 If T is array& 静态成员 value 的值计算为 true 那么将创建对象数组? 但是,这里为什么要创建数组呢?如果我无法使用该数组,需要创建一个数组吗?这不是浪费内存吗?

那为什么下面的语句没有给出任何编译错误呢?

std::cout<<std::is_array<T>::value<<'\n';

我在这里理解错了什么?请帮助我。

最佳答案

N4567 § 8.3.4 数组 [dcl.array]p1(强调我的)

In a declaration T D where D has the form

D1 [ constant-expressionopt] attribute-specifier-seqopt

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is an array type; [...] T is called the array element type; this type shall not be a reference type, the (possibly cv-qualified) type void, a function type or an abstract class type.

因此,语言规则只是禁止您创建“抽象类类型数组”类型。

关于c++ - 对 is_array 模板类的评估感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437082/

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