LearnFrenzy
Sign in Take a free test

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

Storing different types in std::any Answer, explanation & discussion

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

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

main.cpp
#include <any>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::any> bag{1, 2.5, std::string("hi"), 'c'};
    int ints = 0;
    for (const auto& a : bag) {
        if (auto p = std::any_cast<int>(&a)) ints += *p;
        else if (a.type() == typeid(std::string)) std::cout << std::any_cast<std::string>(a) << ' ';
    }
    try { std::any_cast<int>(bag[1]); }
    catch (const std::bad_any_cast&) { std::cout << "bad cast "; }
    std::cout << ints << ' ' << bag[3].has_value() << '\n';
    return 0;
}
  • A hi bad cast 1 1 Correct
  • B hi bad cast 3 1
  • C hi 1 1
  • D bad cast hi 1 1
Correct Answer: Option A

any_cast needs the exact stored type: 2.5 is a double, 'c' a char. The pointer form returns nullptr on mismatch; the value form throws.

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