Can you overload a global operator in a .hpp file?

407 views Asked by At

I wrote an overload for + to add two vector<double>:

vector<double> operator+(vector<double> v, vector<double> u)
{
    int n = (v.size()<u.size()) ? v.size() : u.size();
    vector<double> w;
    for (int j = 0; j<n; ++j)
        w.push_back(v[j] + u[j]);
    return w;
};

If I put in a .cpp file it's fine. But if I put in a .hpp file it generates a lot of errors related to "xutils" system file. Is this normal?

3

There are 3 answers

0
101010 On

You don't have to define a global operator+ to add two std::vectors STL has a facility for this. Defining global operators can really mess things up and cause conflicts. You could use std::transform:

std::vector<double> a {1.0, 2.0, 3.0, 4.0, 5.0};
std::vector<double> b {5.0, 4.0, 3.0, 2.0, 1.0};
std::vector<double> res(a.size());

std::transform(std::begin(a), std::end(a), std::begin(b), std::begin(res), std::plus<double>());

LIVE DEMO

0
KABoissonneault On

If you want to define a global function in a header file, you have to make it inline.

inline vector<double> operator+(vector<double> v, vector<double> u)
{
   ...
}

You can however declare it in a header, then define it in one cpp file.

//x.hpp
vector<double> operator+(vector<double> v, vector<double> u);

//x.cpp
vector<double> operator+(vector<double> v, vector<double> u)
{
    int n = (v.size()<u.size()) ? v.size() : u.size();
    vector<double> w;
    for (int j = 0; j<n; ++j)
        w.push_back(v[j] + u[j]);
    return w;
} // No need for a semi colon here
0
Bathsheba On

Change the prototype to

inline vector<double> operator+(const vector<double>& v, const vector<double>& u)

inline allows the function body to be written in the header.

Passing the parameters by constant reference is unnecessary for compilation but will prevent value copies from being taken, so giving you a performance gain without loss of program stability.

(It's unwise to have a function like this at header scope though as it could pollute your code base. Also, the implementation looks incorrect: you are not including excess elements from the larger vector in your sum).