任何数据类型用于在变量中存储任何类型的值。像JavaScript这样的脚本语言,TypeScript提供 任何数据类型 功能。 C++也提供了这个功能,但只有在Boost库的帮助下。只要将变量的数据类型设置为Any,就可以为变量指定任何类型的值。以下是用任何数据类型声明变量所需的语法: 语法:
null
boost::any variable_name;
注: 要使用boost::any数据类型,程序中需要包含“boost/any.hpp”。
例如:
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; } |
输出:
12 G GeeksForGeeks 12.75 Exception Caught : boost::bad_any_cast: failed conversion using boost::any_cast
参考: http://www.boost.org/doc/libs/1_66_0/doc/html/any.html
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END