gpt4 book ai didi

c++ - 数组是什么类型?

转载 作者:太空狗 更新时间:2023-10-29 20:23:36 24 4
gpt4 key购买 nike

我是引用下面的代码问这个问题

#include <iostream>
using namespace std;

class A {
void foo(){}
};

template <typename T>
void func(T (&a) [1]) {cout << "In array type" << endl;}
template <typename T>
void func(T (*a) [1]) {cout << "In pointer to array type " << endl;}
template <typename T>
void func(T* a) {cout << "in pointer type" << endl;}
template <typename T>
void func(T** a) {cout << "In pointer pointer type" << endl;}
template <typename T>
void func(...) {}

int foo(int a) {return 1;}
int foo1() {return 1;}

int main() {
A a[1];
func<A>(&a);

return 0;
}

数组的类型是什么?从下面的代码我可以看出,当您使用 & 运算符获取数组的地址时,函数调用将解析为带有 T (*a) [1] 的地址并且调用没有歧义,但是当我将代码更改为以下内容时

#include <iostream>
using namespace std;

class A {
void foo(){}
};

template <typename T>
void func(T (&a) [1]) {cout << "In array type" << endl;}
template <typename T>
void func(T (*a) [1]) {cout << "In pointer to array type " << endl;}
template <typename T>
void func(T* a) {cout << "in pointer type" << endl;}
template <typename T>
void func(T** a) {cout << "In pointer pointer type" << endl;}
template <typename T>
void func(...) {}

int foo(int a) {return 1;}
int foo1() {return 1;}

int main() {
A a[1];
func<A>(a); // <-- CHANGE HERE

return 0;
}

我得到一个错误,说对函数的调用不明确。所以虚构的type_of(a)T*是等价的。那么&aT**的类型怎么不等价呢?

我试图向自己解释的方式是,对象数组的类型是 T (&) [N] 并且对象数组的类型是 TT (*) [N]。并且该标准允许从第一个隐式转换(即从 T (&a) [N]T*)但是当您获取数组的地址时它不会隐式地从 T (*) [N]T**。我对么?或者我在推断什么 T (*) [N] 是错误的?

此外,您如何着手阅读像这样的语法的含义。有文档可以引用吗?

谢谢!

最佳答案

... the type of an array to objects is T (&) [N] ...

没有。数组的类型是 T[N]a 的类型是A[1]。您所描述的是对数组的引用,而您的原始示例涉及将指针 传递给类型为A(*)[1] 的数组。您遇到的另一条规则是数组可以衰减为指针。换句话说,T[N] 类型的对象可以隐式转换为T* 类型的对象。

由于隐式转换,您的第二个示例失败了。相关的重载很简单:

template <typename T> void func(T (&)[1]); // (1)
template <typename T> void func(T* ); // (2)

两种重载都是可行的。第一个是精确匹配,而第二个涉及数组到指针的转换。但根据 [over.ics.rank] 中的表格,确定哪个可行候选更好的方法涉及选择转换序列:

  • Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

    • S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form defined by 13.3.3.1.1, excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) or, if not that,

    • the rank of S1 is better than the rank of S2, or S1 and S2 have the same rank and are distinguishable by the rules in the paragraph below, or, if not that,

    • [..]

数组到指针的转换是左值转换,因此它被排除在该要点之外。因此,转换顺序都不是更好的选择,因此我们必须转向其他决胜局。然而,这两个函数都是模板,并且没有一个比另一个更专业。这就是它模棱两可的原因。

关于c++ - 数组是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338988/

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