C & C++

C & C++

Made by DeepSource

Found typedef instead of using CXX-W2029

Anti-pattern
Minor

In C++, using and typedef both perform the same task of declaring type aliases. However, using is more idiomatic as:

  • using can work with templates more efficiently than typedef, as it allows you to specify template parameters later.

  • using can create alias templates that can depend on the underlying type, unlike typedef.

  • using has a clearer syntax for declaring function pointers than typedef, as it avoids the need for parentheses.

Exceptions

typedef is required for exposing C API in public headers.

Bad practice

template<typename T>
typedef T* pointer; // error: cannot use typedef with a template parameter

pointer<int> p; // error: pointer does not name a type
pointer<double> q; // error: pointer does not name a type

Recommended

template<typename T>
using pointer = T*; // pointer is an alias template

pointer<int> p; // p is an int*
pointer<double> q; // q is a double*