需要帮助解码这个 typedef
Need help decoding this typedef
我正在尝试创建对数组的引用。
它是这样工作的:
typedef int array_type[100];
int main() {
int a[100];
array_type &e = a; // This works
}
但后来我试图删除 typedef
,并让同样的东西工作。还没有成功。
int main() {
int a[100];
// int[100] &e = a; // (1) -> error: brackets are not allowed here; to declare an array, place the brackets after the name
// int &e[100] = a; // (2) -> error: 'e' declared as array of references of type 'int &'
}
我对typedef
的理解有什么问题?我怎样才能删除 typedef
,并仍然获得相同的功能。
您需要添加括号来说明这是对数组的引用,而不是某个数组。例如
int (&e)[100] = a;
或使用 auto
or decltype
(均自 C++11 起)使其更简单。
auto& e = a;
decltype(a)& e = a;
如果你想避免这种混淆,这实际上是一个转移到模板化类型的好机会,因为有 std::array
。除其他外,它们提供了在某种程度上统一您需要使用的语法的方法,并且如本例所示,消除了 references/arrays/...
的混淆
int main()
{
std::array<int, 100> a;
std::array<int, 100>& e = a;
}
没有什么能阻止您仍然提供类型别名:
using array_type = std::array<int, 100>;
我正在尝试创建对数组的引用。
它是这样工作的:
typedef int array_type[100];
int main() {
int a[100];
array_type &e = a; // This works
}
但后来我试图删除 typedef
,并让同样的东西工作。还没有成功。
int main() {
int a[100];
// int[100] &e = a; // (1) -> error: brackets are not allowed here; to declare an array, place the brackets after the name
// int &e[100] = a; // (2) -> error: 'e' declared as array of references of type 'int &'
}
我对typedef
的理解有什么问题?我怎样才能删除 typedef
,并仍然获得相同的功能。
您需要添加括号来说明这是对数组的引用,而不是某个数组。例如
int (&e)[100] = a;
或使用 auto
or decltype
(均自 C++11 起)使其更简单。
auto& e = a;
decltype(a)& e = a;
如果你想避免这种混淆,这实际上是一个转移到模板化类型的好机会,因为有 std::array
。除其他外,它们提供了在某种程度上统一您需要使用的语法的方法,并且如本例所示,消除了 references/arrays/...
int main()
{
std::array<int, 100> a;
std::array<int, 100>& e = a;
}
没有什么能阻止您仍然提供类型别名:
using array_type = std::array<int, 100>;