Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Any datatype in C++ boost library

  • Difficulty Level : Easy
  • Last Updated : 25 Jul, 2018

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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!