c++constructordisambiguation

How can I disambiguate a constructor call with parameter from a named instance creation?


In this example, the last line fails to compile. I understand why, but I wonder how I can make the compiler understand that I want to call Class(const int &) to create an unnamed instance, instead of trying to call the undefined default constructor and creating an instance named i:

struct Class {
    Class(const int &) {}
};

void foo() {
    int i;

    // Works
    Class(int(i));

    // Fails
    Class(i);
}

Error in MSVC:

C2371   'i': redefinition; different basic types
E0291   no default constructor exists for class "Class"

Solution

  • You need to use brace initialization so that the grammar does not think you are trying to create an object named i of type Class. For you, that means

    Class{i};
    

    will create an unnamed temporary object that will be destroyed at the end of the full expression.