πŸŽ“ A1Learner
πŸ”
0 of 28 lessons completed

C++ Advanced Introduction

C++ Advanced is the course that follows the intermediate course. It adds new rules for templates and new tools for everyday work.

A function template doubles two types

The doubled function names a placeholder type. One definition serves an int call and a double call.

#include <iostream>

template <typename T>
T doubled(T value) {
  return value * 2;
}

int main() {
  std::cout << doubled(21) << std::endl;
  std::cout << doubled(2.5) << std::endl;
  return 0;
}

A class template holds a string

The Box class template holds one value of the named type. This box holds a string and prints it.

#include <iostream>
#include <string>

template <typename T>
class Box {
public:
  T value;
  Box(T v) {
    value = v;
  }
  void show() {
    std::cout << value << std::endl;
  }
};

int main() {
  Box<std::string> box("hello");
  box.show();
  return 0;
}

Example

#include <iostream>
#include <string>

template <typename T>
T doubled(T value) {
  return value * 2;
}

template <typename T>
class Box {
public:
  T value;
  Box(T v) {
    value = v;
  }
  void show() {
    std::cout << value << std::endl;
  }
};

int main() {
  std::cout << doubled(15) << std::endl;
  Box<std::string> box("advanced");
  box.show();
  return 0;
}

Key points

  • A concept is a rule for templates that names what a type must be able to do.
  • A pipeline over ranges reads values in steps and changes them along the way.
  • A generator makes one value at a time and pauses between values.
  • Threads share the work of one program and run at the same time.
  • Some types move but never copy, so a value changes owner instead of being duplicated.
  • Some boxes may hold a value or hold nothing, so code checks before it reads.
  • Careful code stays correct when errors strike and leaves data in a known state.

In this example, doubled multiplies 15 by 2 and prints 30. The Box object holds the string advanced. Its show method prints the stored string.

Note

Compile with g++ -std=c++20 main.cpp -o main because the new features in this course need the C++20 standard.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does doubled(21) print in the first snippet?