Best practice in C++ for casting between number types
在不同的数字类型之间进行转换的最佳实践是什么?EDCX1、0、EDCOX1、1、EDCX1、2是我在C++中使用最多的类型。
其中
1 2 3 | float f = static_cast<float>(n); float f = float(n); float f = (float)n; |
我通常写EDCOX1,8,但是如果有一个优选的方式,在C++开发社区内是否有任何共识。
我很感激这可能是一个基于意见的问题,可能没有"标准"的方式,在这种情况下,请让我知道没有标准的方式,所以至少我知道:
我知道这个问题出现在一般的铸造方面,但是,我特别感兴趣的是数字,以及在数字类型的方法中是否有特定的最佳实践。
只需使用
C++避免了这一点。另外,C++搜索在搜索它们时更为明显。
使用stroustrup的话(静态广播有什么好处?):
Even an innocent-looking cast can become a serious problem if, during development or maintenance, one of the types involved is changed. For example, what does this mean?:
1 x = (T)y;We don't know. It depends on the type
T and the types of x and y.T could be the name of a class, atypedef , or maybe a template parameter. Maybex andy are scalar variables and(T) represents a value conversion. Maybex is of a class derived fromy 's class and(T) is a downcast. Maybex andy are unrelated pointer types. Because the C-style cast(T) can be used to express many logically different operations, the compiler has only the barest chance to catch misuses. For the same reason, a programmer may not know exactly what a cast does. This is sometimes considered an advantage by novice programmers and is a source of subtle errors when the novice guessed wrong.The"new-style casts" were introduced to give programmers a chance to state their intentions more clearly and for the compiler to catch more errors.
[CUT]
A secondary reason for introducing the new-style cast was that C-style casts are very hard to spot in a program. For example, you can't conveniently search for casts using an ordinary editor or word processor.
[CUT]
casts really are mostly avoidable in modern C++
还可以考虑作为更安全的替代方案(boost.numericconversion库的一部分)的
例如。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> #include <boost/numeric/conversion/cast.hpp> int main() { using boost::numeric_cast; using boost::numeric::bad_numeric_cast; using boost::numeric::positive_overflow; using boost::numeric::negative_overflow; try { int i = 42; short s = numeric_cast<short>(i); // This conversion succeeds (is in range) } catch(negative_overflow &e) { std::cout << e.what(); } catch(positive_overflow &e) { std::cout << e.what(); } return 0; } |
一般来说,对于隐式转换和显式转换(通过
一般来说,这些铸造操作员分为两大类:具体铸造操作人员和传统铸造操作人员。cplusplus.com这样解释:
...In order to control these types of conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast, static_cast and const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.
dynamic_cast (expression)
reinterpret_cast (expression)
static_cast (expression)
const_cast (expression) The traditional type-casting equivalents to these expressions would be:
(new_type) expression
new_type (expression) but each one with its own special characteristics.
在处理任务时,我们(几乎)都使用特定的强制转换。在考虑了这些建议之后,不知何故,这取决于你。
查看资源。