CodeBlanks Logo Icon CodeBlanks

Summary - Modern C++

Combine structured bindings, concepts and ranges to write a data pipeline.

Summary - Modern C++

In this group you met five key tools of C++17 and C++20: safe returns with std::optional, multi-value unpacking with structured bindings, compile-time branches with if constexpr, template constraints with concepts and composable views with ranges.

Together these tools let you write safer, more readable and faster code. Now you will combine what you learned in a small task.

Practice Summary with twice + binding

Write template <typename T> auto twice(T x); in the body use if constexpr to return x * 2 when std::is_integral_v<T> is true, otherwise x. In main bind with auto [mn, mx] = std::pair{twice(5), twice(7)}; and print mn + mx via std::cout.

Starter code

main.cpp
#include <iostream>
#include <type_traits>
#include <utility>

// Write the twice template

int main() {
    // Bind and print the sum
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <type_traits>
#include <utility>

template <typename T>
auto twice(T x) {
    if constexpr (std::is_integral_v<T>) return x * 2;
    return x;
}

int main() {
    auto [mn, mx] = std::pair{twice(5), twice(7)};
    std::cout << mn + mx;
    return 0;
}

Expected output

24

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which tool constrains template parameters?

  • std::optional
  • concepts Correct answer
  • ranges
  • structured bindings

Explanation: concepts constrain templates through a requires clause.

2 Match the tool to its purpose

Term Meaning
std::optional Safe return
structured bindings Multi unpack
if constexpr Compile-time branch
ranges Composable view

3 Complete the if constexpr line

Question
template <typename T>
auto twice(T x) {
    ____ (std::is_integral_v<T>) return x * 2;
    return x;
}
Answer
template <typename T>
auto twice(T x) {
    if constexpr (std::is_integral_v<T>) return x * 2;
    return x;
}

Explanation: if constexpr is a compile-time branch.

All lessons in Advanced