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; } - If I put the
i == {1,2,3}directly in the "if" it doesn't change anything. - Putting brackets around the list, like
i == ({1,2,3}), doesn't change anything neither.
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}); | ~ ^~ | )
{1,2,3}by itself is not anstd::initializer_list, it has no type at all.operator==(i, {1,2,3})compiles, too.operator==(i, {1,2,3})should work as described in the second dupe.==. Using a function is a better idea in this case, although I'd name itinorcontainsinstead ofequal.