3

Example:

std::array<float, 3> vec;

We can do ...

vec = {1.1, 1.2, 1.3};

Why can't we also do the following, for comparison?

vec == {1.1, 1.2, 1.3}

Instead, it appears that we have to do ...

vec == std::array<float, 3>({1.1, 1.2, 1.3})

... or something similar.

Typedef'ing allows me to do something like ...

typedef std::array<float, 3> vector;
vec == vector({1.1, 1.2, 1.3})

But is there a way to just do ... ?

vec == {1.1, 1.2, 1.3}

Can I overload operator== to accomplish this? It would seem that the compiler should know to interpret {1.1, 1.2, 1.3} as whatever is on the left side of the ==. It does it for =. Why not for ==?

Pulseczar
  • 150
  • 8
  • Here is another related question: [Can operators be overloaded for initializer_list literals?](http://stackoverflow.com/questions/14370043/can-operators-be-overloaded-for-initializer-list-literals) – Pulseczar Apr 08 '16 at 02:55
  • The selected answer here satisfied my question, though the answer lacked documentary support: [Compare STL container contents to an initialiser list](http://stackoverflow.com/questions/33781070/compare-stl-container-contents-to-an-initialiser-list) The documentary support seems to be in this answer: [Initializer lists and RHS of operators](http://stackoverflow.com/questions/11420448/initializer-lists-and-rhs-of-operators) – Pulseczar Apr 08 '16 at 03:26

1 Answers1

1

Without an alias, you can use decltype to convert the list

vec == decltype(vec){{1.1, 1.2, 1.3}};

You can explicitly call operator==, but you cannot implicitly convert the list with the comparison operator.

operator==(vec, {{1.1, 1.2, 1.3}});

The only other option I can think of would be std::equal_to but that's uglier:

std::equal_to<decltype(vec)>{}(vec, {{1.1, 1.2, 1.3}});

This answer quotes the standard where it says what an initializer_list can be used for, operators are not in that list.

Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • 2
    Yes, but the question is "Why can't we also do the following...". Why, really? What is the fundamental difference between `vec = { 1, 2, 3 }` and `vec == { 1, 2, 3 }`? The fact that `=` is implicitly declared and `==` is user-declared? – AnT stands with Russia Apr 06 '16 at 17:15
  • in any case, a special `cmp` function that delegates to `std::equal(v.begin(), v.end(), il.begin(), il.end())` would be best, since it avoids the copying. – TemplateRex Apr 06 '16 at 17:22
  • Ok, so the linked duplicate answers my question: the assignment operator is explicitly given special treatment by the language specification. – AnT stands with Russia Apr 06 '16 at 17:37