Site Tools


wiki:hpp-any

Table of Contents

<any>

<any> provides std::any, a type-safe container that can hold a value of any type. At runtime, you check the held type with type() and extract it with std::any_cast<T>(), which throws if the held type doesn't match.

It's useful when you need a heterogeneous collection or when a value's type is not known until runtime, such as config options, plugin return values, or generic event payloads.

Example

This example stores integers, strings, and floating-point numbers in a vector of std::any, then safely retrieves them by checking the held type before casting.

// compile: g++ -std=c++17 -o anyexample anyexample.cpp
// run: ./anyexample
// description: store different types in std::any and retrieve them safely
 
#include <any>
#include <iostream>
#include <vector>
 
int main() {
    std::vector<std::any> values;
    values.push_back(42);
    values.push_back(std::string("hello"));
    values.push_back(3.14);
 
    for (const auto& val : values) {
        if (val.type() == typeid(int)) {
            std::cout << "int: " << std::any_cast<int>(val) << "\n";
        } else if (val.type() == typeid(std::string)) {
            std::cout << "string: " << std::any_cast<std::string>(val) << "\n";
        } else if (val.type() == typeid(double)) {
            std::cout << "double: " << std::any_cast<double>(val) << "\n";
        }
    }
 
    return 0;
}
wiki/hpp-any.md · Last modified: by 127.0.0.1