CodeBlanks Logo Icon CodeBlanks

Standard concepts

Learn standard concepts (Integral, FloatingPoint).

Standard concepts

C++20 ships frequently used concepts in the <concepts> header. The best known are: std::integral, std::floating_point, std::signed_integral, std::unsigned_integral, std::convertible_to, std::same_as and std::copyable.

With them you do not have to write template constraints from scratch. Example: template<std::integral T> T sum(T a, T b). Here T accepts only integral types (int, long, char, ...). This short form means the same as requires std::integral<T>.

Integral and FloatingPoint

std::integral and std::floating_point are the two most used concepts in numeric code. When a template function should accept only integers or only floating-point values, you use these.

Example: template<std::floating_point T> T average(T a, T b) { return (a + b) / T{2}; }. Called with int this function fails to compile, because int is not a floating_point. So type errors are caught at compile time, not at runtime.

Practice Integral-constrained sum function

Write the template function template<std::integral T> T sum(T a, T b) with body return a + b;. In main call sum(3, 4) and print the result with std::cout.

Starter code

main.cpp
#include <iostream>
#include <concepts>

// Write the sum template function here

int main() {
    // Print the result of the sum call
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <concepts>

template<std::integral T>
T sum(T a, T b) {
    return a + b;
}

int main() {
    std::cout << sum(3, 4);
    return 0;
}

Expected output

7

Questions and answers

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

1 Match each concept to its description

Term Meaning
std::integral Integer types
std::floating_point Floating-point types
std::same_as Same type assertion
std::copyable Copyable type

2 the std::integral constraint

Question
template<____ T> T square(T x) { return x * x; }
Answer
template<std::integral T> T square(T x) { return x * x; }

Explanation: The std::integral constraint accepts only integer types.

3 Is std::integral<int> true?

  • Yes, int is an integral type Correct answer
  • Only for unsigned int
  • No, int is not integral
  • Only for long

Explanation: Types like int, long, char and short satisfy std::integral.

All lessons in Advanced