3

An object can be instantiated through assignment operator with an initializer list.

Why can't I compare an object with an initializer list given the fact that the compiler deduces the type of the right hand operand when assigning an initializer list to an object.

#include <string>
#include <map>

class FileInfo
{
public:
    FileInfo(const std::string &name) : mName(name) { }

    bool operator == (const FileInfo& other) const
    {
        return mName == other.mName;
    }

private:
    std::string mName;
};

int main(int argc, char *argv[])
{
    FileInfo f1 = { "f1" };
    FileInfo f2 = { "f2" };

    if (f1 == f2) {} // OK

    if (f1 == { "f2" }) {} // C2059 syntax error: ')'

    if ((f1 = { "f1" }) == f2) { } // OK

    if (f1 == FileInfo{ "f2" }) {} // OK

    return 0;
}

I am trying to understand if there is an objective reason why the comparison fails. Is there a compiler limitation?

Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46
  • You forgot `f1 == "f2"` which is allowed. – StoryTeller - Unslander Monica Dec 28 '16 at 06:12
  • In C++ the compiler has to be told the type, if you are going to declare something on the stack like that (in this case for the purposes of comparison). This is why it's working in your last if statement, but not in your one with an error. In the second to last, it knows the type of f1 already - so it works. – EdH Dec 28 '16 at 06:13
  • @EdH - You are being quite inaccurate. C++ is statically and strongly typed, but it doesn't need to *"to be told the type"*. Types are deduced well enough on their own when the circumstances are right for it. – StoryTeller - Unslander Monica Dec 28 '16 at 06:14
  • I have linked this to a similar question -- the answer to that question covers all the binary operators, not just `==` – M.M Dec 28 '16 at 06:15
  • 2
    tl;dr - a braced list is not an expression - it has to be explicitly mentioned in the grammar wherever it is allowed, and there is no easy way to include it in the grammar for general use with binary operator without making a mess – M.M Dec 28 '16 at 06:16

0 Answers0