Dynamic Type Declaration in C++

Lesson Introduction

Welcome to your first lesson on advanced functional programming techniques in C++. Today, we'll discuss dynamic type declaration, crucial for modern C++ development. Dynamic type declaration allows us to write flexible and maintainable code, which is important in professional settings where clarity and robustness are key.

By the end of this lesson, you will understand how to use the auto and decltype keywords to declare types dynamically. You'll also see practical examples of their application to make functions and templates more manageable.

Recall `auto`

In C++, the auto keyword lets the compiler deduce the type of a variable automatically, simplifying complex type declarations and improving readability.

Here's the basic syntax with an example:

#include <iostream>

int main() {
    int a = 42; // Traditional declaration

    auto b = 42; // Type deduced automatically

    std::cout << "Value of b: " << b << std::endl; // Output: 42
    return 0;
}

Using auto reduces verbosity, which is especially useful with complex types like iterators or user-defined types.

Introduction to `decltype`

The decltype keyword inspects the type of an expression, which is helpful in template programming to deduce types based on expressions. Here is a basic example:

#include <iostream>
#include <type_traits>

int main() {
    int x = 5;
    double y = 10.5;

    // Using decltype to deduce the type of an expression
    decltype(x + y) result = x + y;

    std::cout << result; // 15.5
}

decltype(x + y) deduces the type of x + y, which is double in this case. The syntax decltype(expression) works by deducing the type of expression.

Is there a way to make sure it is a double? Yep, let's see how we can validate types!

Check for the type: Part 1

You can check the type with std::is_same. It is a type trait in C++ provided by the <type_traits> header. It is used to compare two types and determine if they are the same. The trait will return a std::true_type if the types are identical and a std::false_type otherwise. Here’s the syntax used in practice:

#include <type_traits>
#include <iostream>

int main() {
    bool result = std::is_same<int, int>::value; // true
    bool result2 = std::is_same<int, double>::value; // false

    std::cout << std::boolalpha; // Print bools as true/false
    std::cout << "int and int are the same: " << result << std::endl; // Output: true
    std::cout << "int and double are the same: " << result2 << std::endl; // Output: false

    return 0;
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal