Compound requirements
- C++ course
- Advanced
- Lesson 64/83
- 5 min
Learn expression checking with compound requirements.
What is a compound requirement?
A compound requirement checks that an expression is valid and also constrains its return type or that it does not throw. It is written as: { expression } -> concept;.
Example: { a.foo() } -> std::convertible_to<int>;. This requires that the call a.foo() is valid and its return value is convertible to int. This way you guarantee not only that the expression compiles, but that the type is correct. Compound requirements appear inside a requires expression body.
noexcept compound
Adding noexcept to a compound requirement asks that the expression guarantees not to throw: { a.foo() } noexcept;.
Such a check is critical for resource management. Example: a destructor must not throw; to guarantee this at the concept level you write { a.~T() } noexcept;. Types then sign a safety contract at compile time. Moving error handling to this level in templates makes the program more robust.
Practice Define the NothrowDestructible concept
Define the NothrowDestructible concept using the body requires(T a) { { a.~T() } noexcept; }. In main test it with static_assert(NothrowDestructible<int>); and print "Nothrow test passed" with std::cout.
Starter code
#include <iostream>
#include <concepts>
// Define the NothrowDestructible concept here
int main() {
// Test for int and print a message
return 0;
}Sample solution
#include <iostream>
#include <concepts>
template<typename T>
concept NothrowDestructible = requires(T a) {
{ a.~T() } noexcept;
};
int main() {
static_assert(NothrowDestructible<int>);
std::cout << "Nothrow test passed";
return 0;
}Expected output
Nothrow test passed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Return type check
{ a.foo() } ____ std::convertible_to<int>;
{ a.foo() } -> std::convertible_to<int>;
Explanation: The return type in a compound requirement is given after '->'.
2 Compound requirement pieces
| Term | Meaning |
|---|---|
{ expr } |
Expression check |
-> concept |
Return type constraint |
noexcept |
No throw |
requires(T a) |
Parameter binding |
3 What does { expr } noexcept mean?
- The expression is checked at runtime
- The expression always returns true
- The expression only returns an integer
- The expression guarantees not to throw Correct answer
Explanation: A noexcept compound requires at compile time that the expression does not throw.