I'm making a linked list class and I want a convenient default argument for my 'remove()' function.
int size() { return size_; }
int remove(int index = size() - 1);
^[C2352]
This gives me an error a call of a non-static member function requires an object, so I tried
int remove(int index = this->size() - 1);
However the this keyword cannot be used outside of a function. I want to avoid making size_ a public variable, for safety reasons. Note that my class is a template class.
I would appreciate any help for finding a solution for this.
CodePudding user response:
Default arguments must be bound at compile time, so this
is not allowed since it's a runtime value. You could use a free/static function but I don't see how the design is going to work as it wouldn't refer to any specific list instance.
In my opinion the best solution is to use a special value for what you need, eg:
class List
{
static constexpr int LAST_ELEMENT_INDEX = -1;
void remove(int index = LAST_ELEMENT_INDEX)
{
if (index == LAST_ELEMENT_INDEX)
index = size() - 1;
..
}
}