LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Modern C++ Programs · Question 9

Property bag of mixed types with std::any in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Write a PropertyBag storing std::any values by name with a template get<T>(name) returning std::optional<T> (empty if missing or the wrong type); store and read ints, strings and doubles.

Solution
main.cpp
#include <any>
#include <iostream>
#include <map>
#include <optional>
#include <string>

class PropertyBag {
    std::map<std::string, std::any> props_;
public:
    template <typename T>
    void set(const std::string& key, T value) { props_[key] = std::move(value); }

    template <typename T>
    std::optional<T> get(const std::string& key) const {
        auto it = props_.find(key);
        if (it == props_.end()) return std::nullopt;
        if (const T* p = std::any_cast<T>(&it->second)) return *p;
        return std::nullopt;                                   // wrong type
    }
};

int main() {
    PropertyBag w;
    w.set("title", std::string("Dashboard"));
    w.set("width", 1280);
    w.set("opacity", 0.85);
    std::cout << w.get<std::string>("title").value_or("?") << ' '
              << w.get<int>("width").value_or(-1) << ' '
              << w.get<double>("opacity").value_or(1) << ' '
              << w.get<int>("opacity").has_value() << ' '
              << w.get<int>("height").value_or(720) << '\n';
    return 0;
}

Output Verified by compiling and running

Dashboard 1280 0.85 0 720

std::any stores any type; the pointer form of any_cast returns nullptr for a type mismatch, which get turns into an empty optional instead of an exception.

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