0

I'm currently working on a Set-class for a c++ course which is a derivation from vector<T>.

At a point I came to the point where I needed to implement a function called index() which will obviously return (if the set contains it) the index of a object within these set. While writing the whole class I came to the point where I need to overload these index() method, which where both public. So here are my two types of methods: 1st. with 3 params:

size_t index ( T const& x,size_t const& l, size_t const& r) const
{

    if(l > size()||r>size())
        throw("Menge::index(): index out of range.");

    //cut the interval
    size_t m = (l+r)/2;

    // x was found
    if( x == (*this)[m])
        return m;

    // x can't be found
    if( l==m)
        return NPOS;

    //rekursive part
    if( x < (*this)[m])
        return index(l,m,x);

    return index(m+1,r,x);

}

2nd with one param:

bool contains ( T const& elem ) const{
    return index(elem, 0, size()-1)!=NPOS;
}

The point is I don't want to write these 2 methods, it could be combined into one, if possible. I thought about default values for the index() method, so I would write the method-head like:

size_t index (T const& x, size_t const& l=0, size_t const& r=size()-1)const;

which gave me the error: Elementfunction can't be called without a object

After thinking about that error, I've tried to edit it into:

size_t index (T const& x, size_t const& l=0, size_t const& r=this->size()-1)const;

But that gave me the error: You're not allowed to call >>this<< in that context.

Maybe I missed a thing, but please let me know if anyone of you can tell me either it is possible to call a method as a default param, or not.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Philipp Zettl
  • 177
  • 1
  • 3
  • 17

1 Answers1

1

You are not able to use this when defining default arguments.

The this pointer is not allowed in default arguments source.

The usual way is to achieve this is to provide an overload with fewer arguments, which amounts to the initial situation you were avoiding.

size_t index ( T const& x,size_t const& l, size_t const& r) const;
size_t index ( T const& x ) const {
    index( x, 0, size() - 1 );
}

Alternatively, you can consider assigning a magic number as a default argument, which you can test against in your implementation.

#include <limits>

constexpr size_t magic_number = std::numeric_limits<size_t>::max();

size_t index ( T const & x, size_t l = 0, size_t r = magic_number) const
{
    if(r == magic_number) {
        r = size() - 1;
    }

    // Actual implementation
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87