I wrote a function that requires two parameters, but I don't want those two parameters to be 0.
I want to make the compiler know that those two parameters cannot be 0 through some ways, otherwise the editor will report an error in the form of "red wavy line".
I refer to "custom exception class" to solve this problem, but I find this method does not work.
If there are someone knows how to do , I will be very happy, because it takes me a whole day
For example:
#include<iostream>
using namespace std;
int Fuction(int i , int j){
//code
}
int main(){
Funciton(1,1);
Funciton(0,0);
//I don't want i or j is zero
//But if they are still zero , The program will still work normally
return 0;
}
CodePudding user response:
There is no integer type without a 0
. However, you can provoke a compiler error by introducing a conversion to a pointer type. Its a bit hacky, but achieves what you want (I think) for a literal 0
:
#include <iostream>
struct from_int {
int value;
from_int(int value) : value(value) {}
};
struct non_zero {
int value;
non_zero(int*) = delete;
non_zero(from_int f) : value(f.value) {}
};
void bar(non_zero n) {
int i = n.value; // cannot be 0
}
int main() {
bar(non_zero(42));
//bar(non_zero(0)); // compiler error
}
bar
is the function that cannot be called with a 0
parameter. 0
can be converted to a pointer but that constructor has no definition. Any other int
will pick the other constructor. Though it requires the caller to explicitly construct a non_zero
because only one user defined conversion is taken into account.
If you want to throw an exception, thats a whole different story. You'd simply add a check in the function:
if (i == 0) throw my_custom_exception{"some error message"};
CodePudding user response:
If you are using only MSVC you can also take a look at Structured Annotation Language (SAL). It is described on MSDN.
For your case you might be interested in _In_range_(lb,ub)
. An example would be:
void f(_In_range_(1,300) int a, _In_range_(1, 2147483647) int b);
Please note that this will not prohibit calling f(0, 0)
but code analysis will trigger a warning. That warning will be triggered also in cases where you call f(x,x)
and the compiler knows that x
is zero.
In the past I liked to use SAL as it makes the interface clearer and can help reveal errors because the compiler can check more semantics. But now with modern C und the CppCoreGuidelines I am trying to follow the guidelines and so normally I don't need SAL anymore.