_Generic - Linux


The _Generic keyword is used in C++ to provide generic programming capabilities, allowing functions and classes to be defined in a way that works for a variety of data types. It allows the compiler to select the appropriate implementation based on the type of the arguments passed to the function or class.


_Generic((expression), (type-1): (expression-1), ..., (type-n): (expression-n))


  • expression is the expression to be evaluated.
  • type-i is the type of the argument(s) for expression-i.
  • expression-i is the expression to be evaluated if the argument(s) have the type type-i.




// Generic function to calculate the area of a shape
double calculateArea(_Generic(shape,
                            circle: (3.14 * pow(shape.radius, 2)),
                            rectangle: (shape.width * shape.height),
                            triangle: (0.5 * shape.base * shape.height)))
// Generic class for a container
template<_Generic(T, vector: std::vector<T>, list: std::list<T>)>
class Container {
    void add(T element) { ... }
    T get(int index) { ... }
    int size() { ... }

Common Issues

  • Compiler errors: If the compiler cannot determine the type of the arguments passed to the generic function or class, it will result in a compiler error. Ensure the argument types match the specified types in the _Generic expression.
  • Code bloat: Using _Generic can lead to code bloat if there are many different types of arguments. Consider using templates or virtual functions as alternatives.


_Generic can be integrated with other C++ features such as:

  • Templates: Generic functions and classes can be used within templates.
  • Inheritance: Derived classes can inherit generic functions and classes from base classes.
  • Overloading: Generic functions can be overloaded for different types of arguments.

Related Commands

  • std::enable_if
  • std::is_same
  • std::conditional