Skip to content
Related Articles

Related Articles

Any datatype in C++ boost library

View Discussion
Improve Article
Save Article
Like Article
  • 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:

boost::any variable_name;

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


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;


Exception Caught :  boost::bad_any_cast: failed conversion using boost::any_cast


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!