Hi I was stumbling through legacy code, and I came across a wierd method definition/declaration. I have an educated guess of what it does, but I cannot be 100% sure yet.
declaration:
const SomeEnumeratedId (&SomeMethod() const)[SOME_CONSTANT_VALUE];
definition
const SomeEnumeratedId (&SomeClass::SomeMethod() const)[SOME_CONSTANT_VALUE]
{
return some开发者_运维问答MemberArray;
}
My best guess is that it is passing a reference to someMemberArray and that it is guaranteeing that it is of size SOME_CONSTANT_VALUE, but I have never seen the [] notation after the method declaration as it appears, and there are so many parentheses.
Any help greatly appreciated.
It's the declaration of a const
member function taking no parameters and returning a reference to an array of SOME_CONSTANT_VALUE
const
SomeEnumeratedId
s.
It looks easier to understand with a typedef
.
typedef const SomeEnumeratedId SomeArrayType[SOME_CONSTANT_VALUE];
SomeArrayType& SomeClass::SomeMethod() const
{
return someMemberArray;
}
That weird notation, as @Charles has already pointed out is the declaration/definition of a constant method that returns a reference to an array of elements stored as a member.
The syntax is quite bizarre and could (and should probably) be simplified by means of a typedef:
typedef SomeEnumerated array_t[SOME_CONSTANT_VALUE];
const array_t& SomeMethod() const;
Yea, it's a consequence of C's utterly backwards type declaration syntax. It's similar to how, when doing an array typedef, you write this: typedef int myArrayType[3];
, with the [3]
after the new typename, not the original.
If you're really clever you can use {std,tr1,boost}::array
-- worth considering anyway -- so that you end up with:
array<SomeEnumeratedId, SOME_CONSTANT_VALUE>& SomeClass::SomeMethod() const;
instead.
The workarounds with typedefs (explored in other answers) are related, although not quite equivalent as {std,tr1,boost}::array
are wrappers, not just typedefs.
精彩评论