cpp-deduccion-tipo-con-auto

Contextual Type Deduction with auto in C++

  • 2 min

Type deduction by context is a feature that allows the compiler to infer the type of a variable from the context in which it is used.

The goal of type deduction is to make code more concise, easier to read, and more maintainable by avoiding unnecessary code repetition.

In C++, type deduction by context is primarily done using the auto keyword and the decltype functionality.

If you want to learn more, check out the Introduction to Programming Course

Deduction with auto

The auto keyword was introduced in C++11. It allows the compiler to deduce the type of a variable based on the value it is initialized with.

The syntax for using auto is simple:

auto variableName = initializationExpression;
Copied!

For example:

auto number = 42; // `number` is inferred as int
auto message = "Hello World"; // `message` is inferred as const char*
Copied!

In these examples, the compiler automatically infers that number is of type int and message is of type const char* based on the initial values assigned.

Type deduction also works for complex types and for types returned by functions:

auto list = std::vector<std::string>(); // `list` is deduced as std::vector<std::string>
auto myObject = MethodThatReturnsSomething();  // `myObject` is deduced based on the return type of MethodThatReturnsSomething
Copied!

Using decltype for type deduction

decltype is another C++ feature that allows us to deduce the type of an expression without evaluating it. This is useful for obtaining the type of variables.

int x = 5;
decltype(x) y = 10; // `y` is inferred as int
Copied!

Here, decltype(x) deduces the type of x, which is int, and uses it to declare y.

Practical examples