Is there a way of guarding against the resulting binary from the code in t开发者_高级运维his question? Ideally by way of an error at compile time. Example code from the question:
unsigned int nVal = 0;
nVal = -5; // no error!
If you are using g++, the switch -Wsign-conversion
will warn about the conversion, and -Werror
will make that warning an error.
Edit: Apart from @thiton's answer.
With the simple assignment it's not possible. However, if you assign the value in a little special wrapped way, then it can help. i.e.
nVal = -5;
should be replaced with,
Assign<-5>(nVal);
Where, Assign()
looks like,
template<int VAL>
void Assign (unsigned int &nVal)
{
typedef int arr[(VAL >= 0) 1 : -1];
nVal = VAL;
}
Demo.
精彩评论