Question 4
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <string>
#include <variant>
int main() {
std::variant<int, double, std::string> v; // default: the first alternative, int 0
std::cout << v.index() << std::get<int>(v) << ' ';
v = 2.5;
std::cout << v.index() << ' ';
v = "text"; // const char* → std::string
std::cout << v.index() << ' ';
if (auto* p = std::get_if<double>(&v)) std::cout << *p;
else std::cout << "not double";
std::cout << '\n';
return 0;
}
- A 00 1 2 not double Correct
- B 00 1 2 2.5
- C 0 1 2 not double
- D 00 1 0 not double
Correct Answer: Option A
A variant holds one alternative at a time; index() tells which. get_if returns nullptr when the requested type is not active.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!