C++ Basics: Probe a Variant Without Throwing
Use std::get_if when one variant alternative is interesting and other alternatives should follow an ordinary fallback path.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need 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 1Run the example
Save this as variant-get-if-probe-demo.cpp:
#include <iostream>
#include <string>
#include <variant>
using Setting = std::variant<int, std::string>;
void show(const Setting& setting)
{
if (const int* value = std::get_if<int>(&setting)) {
std::cout << "numeric: " << *value << '\n';
} else {
std::cout << "not numeric\n";
}
}
int main()
{
Setting setting{0};
show(setting);
setting = std::string{"automatic"};
show(setting);
const Setting* absent = nullptr;
std::cout << std::boolalpha
<< "null input: " << (std::get_if<int>(absent) == nullptr) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic variant-get-if-probe-demo.cpp -o variant-get-if-probe-demo &&
./variant-get-if-probe-demoObserved output:
numeric: 0
not numeric
null input: trueRead the result
Zero is a successfully found integer, so the first call prints it. The string alternative follows the fallback. A null variant pointer also produces a null result.
Apply it carefully
The type-based overload requires the requested type to occur exactly once in the variant. Test the returned pointer before dereferencing it. Do not retain it across destruction or a change of active alternative. Unlike get, get_if reports a mismatch with nullptr rather than bad_variant_access.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- variant-get-if-probe-demo.cpp variant-get-if-probe-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.