Gizmo
Gizmo

Reputation: 2210

Overloading () operator for std::array gives: error C2039: '()' : is not a member of 'std::array<_Ty,_Size>'

I have a piece of code which looks like this:

std::array<CPlayer,MAX_PLAYERS> Player;
#define Player(playerid) Player[playerid]

And use it then as follow:

Player(id).SomeMethod(some params);

But the definition is just ugly and I want to keep it as much as possible the C++ way, and std::array does have the [] operator but not the () operator so I tried adding this:

template < class T, size_t N > T& std::array<T, N>::operator()(int index)
{
    return this->at(index);
}

But it gives me the following error:

error C2039: '()' : is not a member of 'std::array<_Ty,_Size>'

What can I do about this? I'm clueless.

Upvotes: 1

Views: 726

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129504

It is not possible to add new members (functions or variables) to a class after it was defined.

I personally think that if it's an array, using player[id].SomeMethod(some params); work just as well as your suggestion.

Upvotes: 3

Andrew Tomazos
Andrew Tomazos

Reputation: 68708

Assuming you only want to access the array using function call () syntax (and in no other way) you can hide it as a local static variable in a function:

CPlayer& Player(size_t i)
{
    static std::array<CPlayer,MAX_PLAYERS> PlayerArray;
    return PlayerArray[i];
}

But no idea what you have against subscript [] expressions.

Upvotes: 3

Related Questions