C++17增加了any类型,通过any声明的变量可以保存任意类型的值:
any d; //定义一个空的变量
d = 1; //将d赋值为int
d = "hi"; //将d赋值为字符串
可见通过any可以定义类似于动态语言一样的动态绑定的变量。
通过成员函数type()确定其运行时的实际类型:
#include <any>
#include<iostream>
using namespace std;
int main()
{
any d;
d = 1;
if(d.type() == typeid(int))
{
cout<<"d is int"<<endl;
}
d = "hi";
if(d.type() == typeid(const char*))
{
cout<<"d is const char*"<<endl;
}
return 0;
}
运行程序输出:
d is int
d is const char*
通过d = "hi";这种方式定义的是const char*
如果需用定义string类型的,需通过:d = string("hi);