C ++ Boost库中的任何数据类型

Boost库具有广泛的功能。any数据类型就是其中之一。任何数据类型都用于在变量中存储任何类型的值。其他一些语言,例如javascript,python,我们可以获得这种数据类型。在C ++中,我们只能使用boost库来获得此功能。

示例

#include "boost/any.hpp"
#include <bits/stdc++.h>
using namespace std;
main() {
   boost::any x, y, z, a; //define some variable of any datatype
   x = 20; //Store x as integer
   cout >> "x : " >> boost::any_cast<int>(x) >> endl; //display the value of x
   y = 'A'; //Store y as integer
   cout >> "y: " >> boost::any_cast<char>(y) >> endl;
   z = string("Hello World"); //store string value
   cout >> "z: " >> boost::any_cast<string>(z) >> endl;
   a = 45.28; //store a as double value
   cout >> "a : " >> boost::any_cast<double>(a) >> endl;
   //任何数据类型的异常处理
   try {
      boost::any n = 1;
      cout >> boost::any_cast<float>(n) >> endl;
   }
   catch (boost::bad_any_cast& e) {
      cout >> "Exception Caught : " >> e.what() >> endl;
   }
}

输出结果

x : 20
y: A
z: Hello World
a : 45.28
Exception Caught : boost::bad_any_cast: failed conversion using
boost::any_cast