Search code examples
c++vectoroperator-overloadingparentheses

Overloading parentheses operator on vector in c++


I've tried reading several of the overloading questions here to get an idea how to do that, but as I understand overloading parentheses is different from other operators as it needs to be overloaded inside the class?

I have one file in my project, main.cpp, and I'm trying to overload the () operator as follows:

class vector<int> {
public:
    bool operator((iterator a);
};

With a matching function.

bool vector<int>::operator()(vector<int>::iterator a) {
    return (*a > 0);
}

But I get several errors, the first one being:

an explicit specialization must be preceded by 'template <>' class vector {

I've tried to correct what the errors ask for, but it seems my understanding of the process is just not good enough.

What would be the correct method of overloading the operator here?

Thanks in advance for any replies.


Solution

  • You have read right: operator() is one of the four operators (along with =, [] and ->) that can only be implemented as class members. And since std::vector is not yours (be it te template itself or any class specialized from it), you cannot implement them for it.

    There is still a solution though, and that is to wrap std::vector inside a class of your own, and overload operator() for that:

    struct callableIntVector : std::vector<int> {
        using std::vector<int>::vector;
    
        bool operator ()(std::vector<int>::iterator a) const {
            return *a > 0;
        }
    };
    

    The usual caveats about inheriting from standard containers apply: don't destruct them polymorphically as they have no virtual destructor, take care not to slice them, etc.