Question 5
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
int main() {
std::vector<std::variant<int, std::string, bool>> row{42, std::string("Asha"), true, 7};
int total = 0;
for (const auto& cell : row) {
std::visit([&total](const auto& x) {
using T = std::decay_t<decltype(x)>;
if constexpr (std::is_same_v<T, int>) total += x;
else if constexpr (std::is_same_v<T, std::string>) std::cout << x << ' ';
else std::cout << (x ? "yes " : "no ");
}, cell);
}
std::cout << total << '\n';
return 0;
}
- A Asha yes 49 Correct
- B Asha yes 50
- C Asha 1 49
- D 42 Asha yes 7 49
Correct Answer: Option A
A generic lambda with if constexpr handles each alternative; the ints 42 and 7 are summed.
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!