Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force function parameter to be the same type and not allow using the type constructor to match the given type?

I was a bit surprised finding out this feature in C++, and I didn't expect it 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);
}

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

like image 716
Rookie Avatar asked Oct 26 '25 02:10

Rookie


1 Answers

Make the XY constructor explicit:

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

This will disallow implicit conversions from int to XY, which is what is happening when you call the single-parameter test1 function.

like image 168
juanchopanza Avatar answered Oct 28 '25 17:10

juanchopanza