How to make a function parameter be the same type and not allow the use of a type constructor in accordance with a given type?

I was a little surprised to learn this function in C ++, and I did not expect this to happen.

Here is the code:

struct XY {
    int x,y;
    XY(int v) : x(v), y(v) {}
};

bool test1(const XY &pos){
    return pos.x < pos.y;
}
bool test1(int x, int y){
    return x < y;
}
void functest(){
    int val = 5;
    test1(val);
}

Therefore, I can call a function with an integer parameter, regardless of whether or not such an overload exists, it will use a function of type XY, because it has a constructor of the same type! I do not want this to happen, what can I do to prevent this?

+3
source share
2 answers

Make constructor XYexplicit:

explicit XY(int v) : x(v), y(v) {}

This will turn off implicit conversions from intto XY, which happens when you call a one-parameter function test1.

+6

, . . , .

, :

bool test1(const XY &pos){
    return pos.x < pos.y;
}

bool test1(int x){
    return !x;
}

void functest(){
    int val = 5;
    test1(val);
}

, , ++ "" . " , , ".

1 . , .

-2

All Articles