Skip to content
C++ Basics: Make Empty-Input Validation Explicit

C++ Basics: Make Empty-Input Validation Explicit

November 9, 2026

Use std::all_of for a per-record condition, and add a separate nonempty check when an empty batch must fail validation.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as all-of-empty-validation-demo.cpp:

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    auto positive = [](int value) { return value > 0; };
    std::vector<int> values{2, 5, 8};
    std::vector<int> empty;
    std::cout << std::boolalpha;
    std::cout << "all positive: "
              << std::all_of(values.begin(), values.end(), positive) << '\n';
    std::cout << "empty all: "
              << std::all_of(empty.begin(), empty.end(), positive) << '\n';
    std::cout << "nonempty and valid: "
              << (!empty.empty() && std::all_of(empty.begin(), empty.end(), positive))
              << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic all-of-empty-validation-demo.cpp -o all-of-empty-validation-demo &&
./all-of-empty-validation-demo

Observed output:

all positive: true
empty all: true
nonempty and valid: false

Read the result

The populated range passes. The empty range also passes all_of because it contains no counterexample, while the combined nonempty-and-valid check rejects it.

Apply it carefully

Treat collection-level requirements and element-level requirements separately. An empty configuration, missing measurement set or empty permission list may need its own policy. all_of does not validate that a minimum number of records was provided. Avoid predicates whose side effects depend on being called for every entry: evaluation can stop once a failing element is found.

The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- all-of-empty-validation-demo.cpp all-of-empty-validation-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on