Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::any: a type-safe holder for one value

std::any stores one copyable value of an arbitrary type and preserves its exact type identity for a later any_cast. It can also be empty.

Version: C++23

Syntax

std::any value;
std::any value = object;
T result = std::any_cast<T>(value);

std::any from <any> erases the static type of its stored value while retaining it for runtime checks. std::any_cast<T> retrieves an exact match; a mismatched value cast throws std::bad_any_cast, while the pointer form returns nullptr.

Use it where the set of types is genuinely open, such as plug-in metadata. When alternatives are known, std::variant provides a checkable closed set. reset() makes the holder empty, and emplace<T> replaces the value.

Storing int and asking for long performs no conversion. A move-only type does not satisfy std::any’s copyability contract. A small internal buffer is a possible optimization, not a guarantee; copying can allocate and throw.

Examples

#include <any>
#include <iostream>
#include <string>

int main() {
    const std::any value = std::string{"CKTIS"};
    std::cout << std::any_cast<const std::string&>(value) << '\n';
}

Result

CKTIS

std::any → CKTIS

Sources