Changes between Version 6 and Version 7 of C++Features


Ignore:
Timestamp:
Aug 18, 2025, 2:02:39 PM (2 months ago)
Author:
pett
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • C++Features

    v6 v7  
    6868    };
    6969}}}
     70
     71== Any type ==
     72
     73Hold a copy of a value and its type.
     74
     75{{{
     76#include <any>
     77#include <iostream>
     78#include <string>
     79
     80int main() {
     81    std::any a; // Empty std::any
     82
     83    a = 42; // Stores an int
     84    std::cout << "Value: " << std::any_cast<int>(a) << std::endl;
     85
     86    a = "Hello, C++!"; // Stores a const char*
     87    std::cout << "Value: " << std::any_cast<const char*>(a) << std::endl;
     88
     89    a = std::string("Dynamic string"); // Stores a std::string
     90    std::cout << "Value: " << std::any_cast<std::string>(a) << std::endl;
     91
     92    try {
     93        // Attempting to cast to the wrong type will throw an exception
     94        std::cout << std::any_cast<double>(a) << std::endl;
     95    } catch (const std::bad_any_cast& e) {
     96        std::cerr << "Error: " << e.what() << std::endl;
     97    }
     98
     99    return 0;
     100}
     101}}}