Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++ 부스트 라이브러리의 모든 데이터 유형

<시간/>

부스트 라이브러리에는 다양한 기능이 있습니다. any 데이터 유형이 그 중 하나입니다. 모든 데이터 유형은 모든 유형의 값을 변수에 저장하는 데 사용됩니다. javascript, python과 같은 다른 언어에서는 이런 종류의 데이터 유형을 얻을 수 있습니다. C++에서는 부스트 라이브러리를 사용해야만 이 기능을 얻을 수 있습니다.

예시

#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;
   //exception handling for any datatype
   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