Skip to content
C++ Basics: Probe a Type-Erased Value Without Throwing

C++ Basics: Probe a Type-Erased Value Without Throwing

November 9, 2026

Use the pointer overload of std::any_cast to inspect an optional runtime type match. A failed probe returns nullptr rather than converting the stored value.

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 any-cast-exact-type-demo.cpp:

#include <any>
#include <iostream>
#include <string>

int main()
{
    std::any value = 42;
    if (auto number = std::any_cast<int>(&value)) {
        std::cout << "integer: " << *number << '\n';
    }
    std::cout << "double match: " << (std::any_cast<double>(&value) != nullptr) << '\n';
    value = std::string("ready");
    if (auto text = std::any_cast<std::string>(&value)) {
        std::cout << "text: " << *text << '\n';
    }
    value.reset();
    std::cout << "has value: " << value.has_value() << '\n';
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic any-cast-exact-type-demo.cpp -o any-cast-exact-type-demo &&
./any-cast-exact-type-demo

Observed output:

integer: 42
double match: 0
text: ready
has value: 0

Read the result

The integer probe succeeds, but asking for double fails even though an int could normally convert to double. Replacing the stored object changes the successful probe type, and reset makes the any empty.

Apply it carefully

Check the returned pointer before using it, and do not retain it across replacement or reset of the any. Value and reference any_cast overloads can throw bad_any_cast on a mismatch; the pointer form is useful for branching. std::any stores copy-constructible types. If the allowed alternatives form a known closed set, variant often makes that contract easier to express and check.

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 -- any-cast-exact-type-demo.cpp any-cast-exact-type-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