开发者

Is there a way of causing a compile error if trying to assign a negative number to an unsigned container?

开发者 https://www.devze.com 2023-04-06 16:18 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号