有没有办法禁用从UInt32到char的隐式强制转换? [英] Is there a way to disable implicit casts from UInt32 to char?

查看:58
本文介绍了有没有办法禁用从UInt32到char的隐式强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究以特定协议定义的大量ascii文本作为输入的代码.原始作者将原始协议中的"string(1)"数据类型解释为代码中的char.

I am working on code that takes as input a ton of ascii text defined by specific protocol. The original author interpreted "string(1)" datatypes in the original protocol as chars in the code.

在某些极端情况下,如果您拥有以下代码,则存在许多细微的错误:

There have been a lot subtle bugs in corner cases where you have code such as:

char theChar = whatever();
if(theChar == 7) {...} 

真正的意思是:

if(theChar == '7') {...}

为了尝试一次捕获所有这些,是否有一种方法可以禁用对"char"的隐式强制转换?如果没有,那么追踪所有这些信息的最佳方法是什么?

In order to attempt to catch all of these at once, is there a way to disable the implicit casting to 'char'? If not, what is the best way to go about tracking all of these down?

推荐答案

您应该能够为char编写一个普通的替换类(该类将char作为其数据,并提供了一些强制转换运算符以使其可以使用就像是一个char),不允许对int进行隐式转换,然后执行搜索并将"char"替换为"mychar".这将引发您可以修复的编译器错误,然后,如果您愿意,可以将代码恢复为再次使用char,或者坚持使用您的类.

You should be able to write a trivial replacement class for char (which holds a char as its data, and provides a few cast operators to allow it to be used as if it were a char) that doesn't allow implicit casts to/from ints, and then do a search and replace of 'char' with the 'mychar'. This will throw up compiler errors that you can fix, and then if you wish you can revert the code to using char again, or stick with your class.

这是一个很好的例子,说明在c ++中临时使用宏非常有用的地方...

This is a good example of a place where temporary use of macros is so useful in c++...

这篇关于有没有办法禁用从UInt32到char的隐式强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆