Boost Library มีฟังก์ชันการทำงานที่กว้างขวาง ชนิดข้อมูล Any (any datatype) เป็นหนึ่งในนั้น Any Datatype ใช้เก็บค่าประเภทใดก็ได้ในตัวแปร ภาษาอื่นๆ เช่น JavaScript, Python มีชนิดข้อมูลแบบนี้ ใน C++ เราสามารถได้ฟีเจอร์นี้ได้เฉพาะผ่าน Boost Library เท่านั้น
ตัวอย่าง
#include "boost/any.hpp" #include <bits/stdc++.h> using namespace std; main() { boost::any x, y, z, a; //กำหนดตัวแปรชนิด any x = 20; //เก็บ x เป็น integer cout >> "x : " >> boost::any_cast<int>(x) >> endl; //แสดงค่า x y = 'A'; //เก็บ y เป็น integer cout >> "y: " >> boost::any_cast<char>(y) >> endl; z = string("Hello World"); //เก็บค่า string cout >> "z: " >> boost::any_cast<string>(z) >> endl; a = 45.28; //เก็บ a เป็น double cout >> "a : " >> boost::any_cast<double>(a) >> endl; //Exception Handling สำหรับ 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