Any datatype in C++ boost library

Any datatype is used to store any type of value in a variable. Scripting languages like JavaScript, TypeScript provides any datatype functionality.
C++ also provides this functionality but only with the help of boost library. Any type of value can be assigned to a variable by just making its datatype any. Below is the required syntax for declaring a variable with any datatype:
Syntax:

boost::any variable_name;

Note: To use the boost::any datatype, “boost/any.hpp” needs to be included in the program.

Examples:



boost::any x, y, z, a;
x = 12;
y = 'G';
z = string("GeeksForGeeks");
a = 12.75;
filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to implement the boost/any library
#include "boost/any.hpp"
#include <bits/stdc++.h>
using namespace std;
int main()
{
  
    // declare any data type
    boost::any x, y, z, a;
  
    // give x is a integer value
    x = 12;
  
    // print the value of x
    cout << boost::any_cast<int>(x) << endl;
  
    // give y is a char
    y = 'G';
  
    // print the value of the y
    cout << boost::any_cast<char>(y) << endl;
  
    // give z a string
    z = string("GeeksForGeeks");
  
    // print the value of the z
    cout << boost::any_cast<string>(z) << endl;
  
    // give a  to double
    a = 12.75;
  
    // print the value of a
    cout << boost::any_cast<double>(a) << endl;
  
    // gives an error because it can't convert int to float
    try {
        boost::any b = 1;
        cout << boost::any_cast<float>(b) << endl;
    }
    catch (boost::bad_any_cast& e) {
        cout << "Exception Caught :  " << e.what() << endl;
        ;
    }
  
    return 0;
}

chevron_right


Output:

12
G
GeeksForGeeks
12.75
Exception Caught :  boost::bad_any_cast: failed conversion using boost::any_cast

Reference: http://www.boost.org/doc/libs/1_66_0/doc/html/any.html



My Personal Notes arrow_drop_up

Sometimes you never realize the value of a moment until it becomes a memory

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.