I have a legacy interface that has a function with a signature that looks like the following:
int provide_values(int &x, int &y)
x
and y
are considered output parameters in this function. Note: I'm aware of the drawbacks of using output parameters and that there are better design choices for such an interface. I'm not trying to debate the merits of this interface.
Within the implementation of this function, it first checks to see if the addresses of the two output parameters are the same, and returns an error code if they are.
if (&x == &y) {
return -1; // Error: both output parameters are the same variable
}
Is there a way at compile time to prevent callers of this function from providing the same variable for the two output parameters without having such a check within the body of the function? I'm thinking of something similar to the restrict
keyword in C, but that only is a signal to the compiler for optimization, and only provides a warning
when compiling code that calls such a function with the same pointer.
provide_values(array[time()%10], array[time()%10])
?__restrict__
keyword. It will warn at compile-time if it can see both parameters point to the same variable, but not when you have run-time pointers like @RaymondChen mentioned.std::is_same<T1, T2>::value
,std::is_base_of<T1,T2>::value
, andstd::is_base_of<T2, T1>::value
all giving afalse
result). Then let the type system do the work - preventing passing of two arguments of the same type also means that two arguments cannot have the same address (assuming the program doesn't exhibit undefined behaviour, in which case all bets are off). It would be easier to simply pass a single struct (which contains both values to be returned by the caller) by reference.