LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 5

std::visit with a generic lambda Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links