Constructor of class with conflicting name

让人想犯罪 __ 提交于 2019-12-23 16:02:05

问题


I am using clang to compile my code using the c++14 dialect. 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 class named x whose name conflicts with a function with the same name. To distinguish between x the class and x the function, one has to use the class identifier. 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 function f with an x object by building it on the go. However, if I use f(x(33)) it interprets it as an ill-formed call to the function x, and if I use f(class x(33)) it just yields a syntax error.

There are obvious workarounds, but I would like to know if there is anything more elegant than typedefing the class x with a temporary alias or explicitly instantiating an item that will annoy me by living in the whole scope of the calling function while I need it only in the line of the function call.

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


回答1:


All you need is a pair of parentheses:

f((class x)(33));

Or for more parameters, also use uniform initialization:

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


来源:https://stackoverflow.com/questions/31675004/constructor-of-class-with-conflicting-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!