Why Doesn’t reinterpret_cast Force copy_n for Casts between Same-Sized Types?

why doesn’t reinterpret_cast handle that for me? One reason is that the size, alignment, and bit representations aren’t specified, so such a conversion wouldn’t be portable. However, that wouldn’t really justify making the behaviour undefined, just implementation-defined. By making it undefined, the compiler is allowed to assume that expressions of unrelated types don’t access the … Read more

Lexical cast from string to type

I like using locate, which works on built-in types: >>> from pydoc import locate >>> locate(‘int’) <type ‘int’> >>> t = locate(‘int’) >>> t(‘1’) 1 …as well as anything it can find in the path: >>> locate(‘datetime.date’) <type ‘datetime.date’> >>> d = locate(‘datetime.date’) >>> d(2015, 4, 23) datetime.date(2015, 4, 23) …including your custom types: >>> … Read more

When to use a Cast or Convert

Cast when it’s really a type of int, Convert when it’s not an int but you want it to become one. For example int i = (int)o; when you know o is an int int i = Convert.ToInt32(“123″) because “123” is not an int, it’s a string representation of an int.

What is the modern, correct way to do type punning in C++?

First of all, you assume that sizeof(long) == sizeof(int) == sizeof(float). This is not always true, and totally unspecified (platform dependent). Actually, this is true on my Windows using clang-cl and wrong on my Linux using the same 64-bit machine. Different compilers on the same OS/machine can give different results. A static assert is at … Read more

Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting long to int?

As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract: A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. An example cited from §15.26.2 […] the following code is … Read more