Here is a proposal for the Blender Style guide to cover type casting topic in C++ code.
Motivation
The style of casting is not consistent across different files even within the same module. Sometimes the cast is not const or type correct, sometimes is overly verbose. Having a single guideline of casts should help the code quality, readability, and onboarding.
The core principles
There are few things which are important when it comes to type casting. This is what the proposal follows:
- Readability of simple cases.
- Const-correctness.
- Type-safety.
Proposal
This is rather short proposal:
- For arithmetic and enumeration types use the functional-style cast (2). For example,
int(float_value),float(int_value). - For other type conversions use
static_castwhen possible andreinterpret_castorconst_castotherwise.
The functional-style arithmetic type is chosen over C-style due to the following reasons:
- Personal experience working with various templated numerical libraries, where it is sometimes required to construct special arithmetic-like type from a templated functor. In those cases
T(something)shows the intent more clearly. - Consistent with the way how cast is done in Python.
- Looks the same as static/reinterpret/const cast.
Some possible extensions for the proposal to cover typical cases in the code:
- Use
static_cast<MyClass*>(user_data)to castvoid *user_datatoMyClass *. In other words, usestatic_castand notreinterpret_cast<>to cast from void pointer to an object pointer.
Feedback is welcome!
