Vladimir
Vladimir

Reputation: 510

Call Operator() for std::shared_ptr instance

CustomDynamicArray class wraps std::vector and gives an access to its items by pair of indexes via overloaded operator operator()

CustomCell& CustomDynamicArray::operator()(size_t colIdx, size_t rowIdx)

It makes possible to address an array items a natural way:

CustomDynamicArray _field;
_field(x, y) = cell;
const CustomCell& currentCell = _field(x, y);

But since I covered my variable into std::shared_ptr I have an error

std::shared_ptr<CustomDynamicArray> _fieldPtr;
_fieldPtr(x, y) = cell; // Error! C2064 term does not evaluate to a function taking 2 arguments
const CustomCell& currentCell = _fieldPtr(x, y); // Error! C2064    term does not evaluate to a function taking 2 arguments

How can I fix this compile error? Now I can see only way to use this syntax:

(*_newCells)(x, y) = cell;

Upvotes: 2

Views: 1785

Answers (2)

songyuanyao
songyuanyao

Reputation: 172884

std::shared_ptr is smart pointer which behaves like raw pointers, you can't call operator() on the pointer directly like that. You could dereference on the std::shared_ptr then call the operator().

(*_fieldPtr)(x, y) = cell;
const CustomCell& currentCell = (*_fieldPtr)(x, y);

Or invoke operator() explicitly (in ugly style).

_fieldPtr->operator()(x, y) = cell;
const CustomCell& currentCell = _fieldPtr->operator()(x, y);

Upvotes: 7

Hatted Rooster
Hatted Rooster

Reputation: 36463

You have to deref the pointer first:

(*_fieldPtr)(x, y) = cell;
const CustomCell& currentCell = (*_fieldPtr)(x, y);

Upvotes: 1

Related Questions