-2

Can I create my own overload of == for valarray<double>? I don't like the default behavior where x==y (for valarrays x and y) returns a valarray<bool>. I want it to return a single bool, true if x and y have the same values.

Can I overwrite the default overload of operator== for valarray<double>.

a06e
  • 18,594
  • 33
  • 93
  • 169
  • 5
    How is this question different from https://stackoverflow.com/questions/31125807/best-way-to-test-for-equality-of-two-valarraydouble? – Anton Savin Jun 29 '15 at 21:59
  • Why don´t you make just a "normal" non-operator function? – deviantfan Jun 29 '15 at 21:59
  • Of Course!you can provide your own overload that has more precedence, but you **can't** overwrite the default (which you don't like it's behavior!).the trick here is to make sure that everywhere you compare valarray's, the unqualified lookup is going to find this overload. – marc_s Jun 29 '15 at 22:31

1 Answers1

7

Sure. You can't "overwrite the default", you but you can provide your own overload that will have higher precedence:

#include <iostream>
#include <valarray>

bool operator==(const std::valarray<double>& a, const std::valarray<double>& b)
{
    std::cout << "hi\n";
    return true;
}

int main(int argc, char *argv[])
{
    std::valarray<double> a, b;
    a == b; // prints hi
}

Since operator== is a non-member function template, a function that isn't a template will be preferred in overload resolution. The key is to make sure that everywhere you compare valarray's, unqualified lookup will find this overload.

Of course, it's a lot safer to just write:

bool equals(const std::valarray<double>&, const std::valarray<double>&);
Barry
  • 286,269
  • 29
  • 621
  • 977
  • Try `equals(x + y + z, t)`, where `x`, `y`, `z` and `t` are `valarray`. It won't work because `x+y+z` returns a "proxy" expression class which won't match `valarray` in overload resolution. How can I fix that? – a06e Jun 30 '15 at 14:27