Read a variant only when it holds the expected type.
C++: get_if returns a null pointer rather than throwing for another active alternative.
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <array>
#include <algorithm>
#include <numeric>
#include <map>
#include <unordered_map>
#include <set>
#include <queue>
#include <stack>
#include <deque>
#include <tuple>
#include <bitset>
#include <memory>
#include <optional>
#include <variant>
#include <functional>
#include <charconv>
#include <regex>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <iomanip>
#include <cmath>
#include <cctype>
#include <limits>
#include <chrono>
#include <thread>
#include <future>
#include <mutex>
#include <atomic>
#include <condition_variable>
int main() {
std::cout << std::boolalpha;
std::variant<int,std::string> value=std::string("hello");
if (const auto* text=std::get_if<std::string>(&value)) std::cout << *text << "\n";
}
Expected output EXAMPLE
hello
Details
Save as snippet.cpp; compile with g++ -std=c++17 -Wall -Wextra snippet.cpp -pthread -o snippet, then run ./snippet. get_if returns a null pointer rather than throwing for another active alternative.
Tested on Ubuntu 24.04.5 LTS · · g++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 · g++ 4:13.2.0-7ubuntu1
Test inputs, results and environment
The exact published code ran in a dedicated Linux test container with prepared inputs. Unprivileged snippet process, external networking disabled, read-only root filesystem, and a fresh temporary working directory. Fixtures and output records are isolated from the application database. Testing covers this example and its stated checks, not every input, operating system, or runtime version. The Linux container shares its host's kernel; this is not a native Windows test.
- Architecture / host kernel
- x86_64 / 6.18.54.1-microsoft-standard-WSL2
- Snippet identity / locale
- uid=65534, gid=65534 (unprivileged) / C.UTF-8
- Interpreter invocation
g++ -std=c++17 -Wall -Wextra -Werror snippet.cpp -pthread -lm -o snippet && ./snippet- Container image ID
sha256:32dc2d998158b6554c99b73b533f423696a0f3e31e8cbea9db10b5eee9a2fadd- Code SHA-256
143fa2238e818617b0d2eb6871b74c039f6647c3b3e8d1158351f5f51973cd4e- Dependencies
- g++ 4:13.2.0-7ubuntu1
Test input setup
These are the prepared inputs used by the test harness. See Details above for the prerequisites and how to run this example.
# No input files required.
Observed standard output
hello
Exit code: 0. Standard error: empty. Validation: Exact stdout comparison. System-dependent values above are one recorded run.