此代码行末尾的方括号是什么意思

What do the square brackets at the end of this code line mean?

本文关键字:方括号 是什么 意思 代码      更新时间:2023-10-16

我对C++相当陌生,在遇到一个参考站点时,我遇到了以下代码片段,从那以后我一直在努力分解它。

这就是我仍在努力弄清楚的:

int (*(*callbacks[5])(void))[3]

我已经通读了部分C++帮助书籍,并且(大致(了解优先级流程。但是看到许多操作员聚集在一起让我很失望,我相当困惑。我看过其他的例子和解释(在这里(,但右边额外的 [3] 下标只会让我的事情复杂化。

我想知道我应该

如何处理这种复杂的代码,即我从哪里开始,我应该遵循什么顺序等。

真的很感激你的帮助!谢谢!!

这是一个包含 5 个指针的数组,指向不带参数的函数,并返回指向 3 个整数数组的指针。

我只是因为 cdecl.org 告诉我才想通的。 这是typedef使事情更容易阅读的地方之一:

typedef int (*PointerToArrayOfInts)[3];
typedef PointerToArrayOfInts (*FunctionReturningPointerToArray)(void);
FunctionReturningPointerToArray callbacks[5];

这是一个原始的内省"漂亮打印机"的开始,它让C++编译器本身为您分解内容:

#include <iostream>
template <typename T>
struct introspect;
template <>
struct introspect<int> {
    static std::ostream& prettyPrint(std::ostream& os) { return os << "int"; }
};
template <typename T>
struct introspect<T*> {
    static std::ostream& prettyPrint(std::ostream& os) {
        os << "pointer to ";
        return introspect<T>::prettyPrint(os);
    }
};
template <typename T, std::size_t N>
struct introspect<T[N]> {
    static std::ostream& prettyPrint(std::ostream& os) {
        os << "array of " << N << " (";
        introspect<T>::prettyPrint(os);
        return os << ")";
    }
};
template <typename Res>
struct introspect<Res(void)> {
    static std::ostream& prettyPrint(std::ostream& os ) {
        os << "function returning (";
        introspect<Res>::prettyPrint(os);
        return os << ")";
    }
};
int main() {
    int (*(*callbacks[5])(void))[3];
    introspect<decltype(callbacks)>::prettyPrint(std::cout) << 'n';
    return 0;
}

输出:

array of 5 (pointer to function returning (pointer to array of 3 (int)))
int (*(*callbacks[5])(void))[3]

将回调声明为指向函数的指针的数组 5 (void( 返回指向 int 的数组 3 的指针