我正在使用一个使用无符号整数作为某些数据索引的C库。但有时,函数会将这些索引作为带符号的返回,以便在函数无法返回索引时返回-1
。
我该如何避免implicit conversion changes signedness
警告,并在转换不可能时抛出运行时错误?您是否建议封装库函数以使用异常进行错误处理并仅返回正确的值?
是否有一种标准的方法来实现这个:
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
// pointless c function to demonstrate the question
// parse the string to an unsigned integer, return -1 on failure
int atoui(char const* str) {
char* pend;
long int li=strtol(str, &pend, 10);
if ( errno!=0 || *pend!='\0' || li<0 || li>INT_MAX ) {
return -1;
} else {
return li;
}
}
// --8<---
#include <stdexcept>
// How to do this properly?
unsigned int unsign(int i) {
if(i<0) {
throw std::runtime_error("Tried to cast negative int to unsigned int");
} else {
return static_cast<unsigned>(i);
}
}
int main() {
unsigned int j=unsign(atoui("42")); // OK
unsigned int k=unsign(atoui("-7")); // Runtime error
}
std::is_integral
文档 中:template< class T > inline constexpr bool is_integral_v = is_integral<T>::value;
- phuclv