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

C++ Abbreviated Templates

An abbreviated template uses auto with a concept in place of a full template head. The short form names the rule right where the value is used.

One short function, two types

The show function takes a std::integral auto parameter. One definition serves an int call and a char call.

#include <iostream>
#include <concepts>

void show(std::integral auto value) {
  std::cout << value << std::endl;
}

int main() {
  show(42);
  show('A');
  return 0;
}

The same function in long form

This program writes the template head in full. Its calls print the same two lines as the short form.

#include <iostream>
#include <concepts>

template <std::integral T>
void show(T value) {
  std::cout << value << std::endl;
}

int main() {
  show(42);
  show('A');
  return 0;
}

A constrained auto variable

The total variable carries a constrained auto type. The sum of 20 and 22 is a whole number, so the line compiles and prints.

#include <iostream>
#include <concepts>

int main() {
  std::integral auto total = 20 + 22;
  std::cout << total << std::endl;
  return 0;
}

Two constrained parameters

The addValues function gives each parameter its own rule. An int and a long meet in one call, and two ints meet in the next.

#include <iostream>
#include <concepts>

auto addValues(std::integral auto a, std::integral auto b) {
  return a + b;
}

int main() {
  std::cout << addValues(20, 22L) << std::endl;
  std::cout << addValues(5, 6) << std::endl;
  return 0;
}

Example

#include <iostream>
#include <concepts>

void report(std::integral auto value) {
  std::cout << "Count: " << value << std::endl;
}

void report(std::floating_point auto value) {
  std::cout << "Price: " << value << std::endl;
}

int main() {
  report(3);
  report(2.5);
  return 0;
}

Key points

  • A constrained auto parameter makes a function a template.
  • Each call fixes the type from the argument it is given.
  • The long form writes a template head above the same function.
  • Both forms make the same template and print the same lines.
  • A variable can carry a constrained auto type too.
  • Two parameters can carry two different rules in one function.

In this example, two report functions use the abbreviated form with different concepts. The int call prints the Count line. The double call prints the Price line.

Note

The short form and the long form make the same template, just written two ways.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line does the char call print in the first snippet?