我有一个函数声明为:
void foo(unsigned int x)
Run Code Online (Sandbox Code Playgroud)
如何检查 foo() 没有收到负数?我希望如果我调用 foo(-1) 会抛出异常,但当然由于 x 会自动转换为无符号,因此我无法检查其正性,例如:
if not(x>=0){ do_something();};
Run Code Online (Sandbox Code Playgroud)
或类似的检查。
实际上没有什么好的方法可以做到这一点,但是您可以通过一些技巧来做到这一点:
1) 声明一个未定义的更好匹配:
void foo(unsigned int x) {
//do something
}
void foo(int x);
Run Code Online (Sandbox Code Playgroud)
2)使用typeid来判断类型。