Search code examples
c++c++11shared-ptr

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;

Solution

  • 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);