Constructor of class with conflicting name

I am using clang to compile my code using C ++ 14 dialogs. Take the following example:

class x
{
    int _i;

public:

    x(int i)
    {
        this->_i = i;
    }
};

void x()
{
}

void f(class x my_x)
{
    // Do something here
}

int main()
{
    /*
     f(x(33)); // Doesn't work
     f(class x(33)); // Doesn't work
    */

    // This works:

    class x my_x(33);
    f(my_x);

    typedef class x __x;
    f(__x(33));
}

      

Here I have a named class x

whose name conflicts with a function of the same name. To distinguish between x

class and x

function, you need to use an identifier class

. This works for me in all situations, but I could never find a way to directly call the constructor for x

.

In the previous example, I want to provide a function f

with an object x

, building it on the fly. However, if I use f(x(33))

it interprets it as a poorly formed function call x

, and if I use f(class x(33))

it just gives a syntax error.

There are obvious workarounds, but I would like to know if there is something more elegant than typing class x with a temporary alias or explicitly instantiating the element, which will annoy me by living in the entire scope of the calling function while I this is only needed in the function call line.

Maybe there is a simple syntax that I am not aware of?

+3


source to share


1 answer


All you need is a pair of parentheses:

f((class x)(33));

      



Or use uniform initialization for more parameters as well:

f((class x){1, 2, 3});

      

+9









All Articles