Search code examples
c++most-vexing-parse

Is there a way to force the "most vexing parse" to be an error, even on a class by class basis?


Is it possible (with any modification of class A) to have the following work? i.e., make the most vexing parse an error?

class A {
};

int main() {
    A a(); // can this be forced to be an error??
    A b;   // this should work
}

Solution

  • No modification of the class A will have any effect on how a declaration A a(); is parsed. The parser determines that this is a function declaration before it even bothers to look at the definition of A. In fact the definition of A doesn't even need to be visible to parse this statement; A forward declaration is sufficient.

    However compilers generally have a warning for this and you can probably turn that into an error. For example with clang you can use the flag -Werror=vexing-parse.

    struct A;
    
    A a(); // no error
    
    int main() {
        A a(); // error
    }
    

    clang++ -std=c++11 -Weverything -Werror=vexing-parse main.cpp

    main.cpp:6:8: error: empty parentheses interpreted as a function declaration [-Werror,-Wvexing-parse]
        A a();
           ^~
    main.cpp:6:8: note: replace parentheses with an initializer to declare a variable
        A a();
           ^~
           {}
    1 error generated.
    

    Although technically speaking A a(); isn't the syntax known as the most vexing parse. That would be:

    A a(B());