Alexandre Man
Alexandre Man

Reputation: 9

C++ operator== doesn't work but an actual function does

I got a function:

bool equal(int var, std::initializer_list<int> list)
{
    return std::find(list.begin(), list.end(), var) != list.end();
}

which works, I got no error when I use the function. But when I create an operator overload with the same parameters, it gives me an compiling error E0029 when using the operator ==.

bool operator==(int var, std::initializer_list<int> list)
{
    return std::find(list.begin(), list.end(), var) != list.end();
}

The function definitions don't give me errors, it's when I call the operator with the parameters that it does.

Here's the full thing:

#include <iostream>
#include <initializer_list>
#include <algorithm>



bool operator==(int var, std::initializer_list<int> list)
{
    return std::find(list.begin(), list.end(), var) != list.end();
}
bool equal(int var, std::initializer_list<int> list)
{
    return std::find(list.begin(), list.end(), var) != list.end();
}

int main()
{
    bool b;
    for (int i = 0; i <= 5; i++)
    {
        b = (i == {1,2,3});    // this line gives me a compiling error
        b = equal(i, {1,2,3}); // this line doesn't
        if (b) std::cout << "true\n";
        else std::cout << "false\n";
    }
    return 0;
}

I tried using another software, I'm currently using Visual Studio Code 22, and I tried compiling it in Codeblocks and in Linux with gcc, it gives me an error the same way.

Codeblocks:

||=== Build file: "no target" in "no project" (compiler: unknown) ===|
test.cpp||In function 'int main()':|
test.cpp|113|error: expected primary-expression before '{' token|
test.cpp|113|error: expected ')' before '{' token|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

In gcc with the command "gcc test.cpp -o test.exe":

test.cpp: In function ‘int main()’:
test.cpp:113:19: error: expected primary-expression before ‘{’ token
  113 |         b = (i == {1,2,3});
      |                   ^
test.cpp:113:18: error: expected ‘)’ before ‘{’ token
  113 |         b = (i == {1,2,3});
      |             ~    ^~
      |                  )

Upvotes: 0

Views: 79

Answers (0)

Related Questions