Skip to content
DryPerspective edited this page Oct 6, 2023 · 3 revisions

Class dp::any provides type-safe storage for an instance of any copy-constructible type. An instance of dp::any may be constructed with and reassigned a value as many times as needed. Default-constructed instances of any are considered empty, and do not contain anything. The value can be retrieved via templated free function dp::any_cast. If dp::any_cast is called on an empty any, or with a type on an any which does not contain that type, an exception will be thrown.

dp::any uses the small storage optimization - sufficiently small types will be stored on the stack rather than being dynamically allocated. It also avoids RTTI when checking its type, except as a backup (the likely case being a failed any_cast) and of course in calls to type()

List of Features

reset Destroys the contained object
swap Swaps the held values of two objects
has_value Checks if an any currently has a value
type Retrieves a std::type_info corresponding to the held type
any_cast Retrieves the held value

Sample Code

#include "cpp98/any.h"

int main(){
 dp::any an(10); //Any now contains an int
 an = 50.5;      //Any now contains a double
 an = UnicodeString("Hello world"); //Any now contains a UnicodeString

 try{
    int x = dp::any_cast<int>(an); //Any does not currently contain an int, exception thrown
 }
 catch(dp::bad_any_cast& e){
    Print(e.what());  //NB: See borland compatibility on exceptions if on Borland
 }
 
 Print(dp::any_cast<UnicodeString>(an)); //Prints "Hello world"
}

Clone this wiki locally