C++ boost 庫中的任何資料型別
boost 庫有著廣泛的功能。其中之一便是 any 資料型別。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;
//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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP