Skip to content

std::any

std::any provides a typesafe container for a single object of any type.

Having an object someObject of type std:: any

  • you can ask for its type: someObject.type() == typeid(int)
  • knowing the type you can safely cast: auto val = std::any_cast<int>(someObject)

Example function processing a param of type std::any:

#include <any>

void CheckAny(const std::any& anyVal)
{
    // Expect some possible types

    if (!anyVal.has_value())
    {
        std::cout << "not set\n";
    }
    else if (anyVal.type() == typeid(int))
    {
        std::cout << std::format("has int type with value {}\n", std::any_cast<int>(anyVal));
    }
    else if (anyVal.type() == typeid(std::string))
    {
        std::cout << std::format("has std::string type with value {}\n", std::any_cast<std::string>(anyVal));
    }
    else
    {
        std::cout << std::format("has unexpected type {}\n", anyVal.type().name());
    }
}

Client code:

    std::any x;
    CheckAny(x);

    x = 42;
    CheckAny(x);

    x = std::string("Hello");
    CheckAny(x);

    x = 3.14;
    CheckAny(x);

Output:

not set
has int type with value 42
has std::string type with value Hello
has unexpected type double