Open In App

Any datatype in C++ boost library

Improve
Improve
Like Article
Like
Save
Share
Report

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;




// 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;
}


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



Last Updated : 25 Jul, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads