astro-informatics/sopt

Modernise: Replace typedefs with using aliases

Closed this issue · 0 comments

Replacing C-style typedefs with using aliases.

Reasoning from learncpp.com

Typedefs are still in C++ for backwards compatibility reasons, but they have been largely replaced by type aliases in modern C++.

Typedefs have a few syntactical issues.

  1. First, it’s easy to forget whether the name of the typedef or the name of the type to alias comes first. Which is correct?
typedef Distance double; // incorrect (typedef name first)
typedef double Distance; // correct (aliased type name first)

It’s easy to get backwards. Fortunately, in such cases, the compiler will complain.

  1. Second, the syntax for typedefs can get ugly with more complex types. For example, here is a hard-to-read typedef, along with an equivalent (and slightly easier to read) type alias:
typedef int (*FcnType)(double, char); // FcnType hard to find
using FcnType = int(*)(double, char); // FcnType easier to find

In the above typedef definition, the name of the new type (FcnType) is buried in the middle of the definition, whereas in the type alias, the name of the new type and the rest of the definition are separated by an equals sign.

  1. Third, the name “typedef” suggests that a new type is being defined, but that’s not true. A typedef is just an alias.

Typedefs cannot work with templates

See this answer on SO for some subtle differences between them. Particularly, using aliases are compatible with templates whereas typedefs are not.

The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future.

They are essentially the same but using provides alias templates which is quite useful. One good example I could find is as follows:

namespace std {
 template<typename T> using add_const_t = typename add_const<T>::type;
}

So, we can use std::add_const_t<T> instead of typename std::add_const<T>::type

Also, as per this Microsoft docs page:

A limitation of the typedef mechanism is that it doesn't work with templates. However, the type alias syntax in C++11 enables the creation of alias templates:

template<typename T> using ptr = T*;

// the name 'ptr<T>' is now an alias for pointer to T
ptr<int> ptr_int;

Closed by #372