anderssinho
anderssinho

Reputation: 298

Check if element already exist within template class

I have built a class called Set which inherits from the base-class called ISet and it looks something like this.

template <class T>
class Set : public ISet<T>
{
public:
    Set();
    ~Set();
    Set(const Set &origin);
    Set operator=(const Set &origin);

    bool insert(T element);
    bool remove(T element);
    int size()const;

private:
    T *arr;
    int cap, nrOfElement;

    void deepCopy(const Set &origin);
    void freeMemory();
};

I should now build the function called insert, which should insert a element of type T if, and only if, it does not exist already. I'm having a problem to understand how to solve this since T element should be able to be of any type. I have tried something like:

bool Set<T>::insert(T element)
{
    bool added = false;

    if (nrOfElement == 0)
    {
        this->arr[0] = element;
        this->nrOfElement++;
    }
    else
    {
        for (int i = 0; i < this->nrOfElement; i++)
        {
            if (this->arr[i] == element)
            {
                i = this->nrOfElement;
                added = true;
            }
        }
        if (added == false)
        {
            this->arr[nrOfElement++] = element;
        }
    }

    return added;
}

But since some of the classes I'm trying to insert as T doesn't have the operator==, it can't handle the == operation above I try to do. Should I try to type_cast it? Or how do you solve this?

Upvotes: 0

Views: 281

Answers (1)

eerorika
eerorika

Reputation: 238401

Either

  1. Document that your template works only with types that are equality comparable or

  2. Store a function object within your template class that can be used to compare the objects. The type of the comparison object needs to be a template argument. You can default to std::equal_to<>, which will use operator== unless specialised. The user must provide a custom comparison object in order to use the template with non-equality-comparable types. This is how standard containers deal with comparisons. If the user cannot implement such comparison object, then there is no way to know whether one object is a duplicate of another.

Upvotes: 2

Related Questions