我存储了一个指向 type_info
对象的指针。
int MyVariable = 123;
const std::type_info* Datatype = &typeid(MyVariable);
我如何使用它来将另一个变量类型转换为该类型?我试过这个,但它不起作用:
std::cout << ((*Datatype)3.14) << std::endl;
使用类型转换的函数形式也不起作用:
std::cout << (*Datatype(3.14)) << std::endl;
最佳答案
很简单,您不能使用 type_info
来做到这一点。此外,在您的示例中,DataType
不是类型,它是指向type_info
类型对象的指针。你不能用它来转换。转换需要类型,而不是指针或对象!
在 C++0x 中,您可以这样做,
int MyVariable = 123;
cout << (decltype(MyVariable))3.14 << endl;
cout << static_cast<decltype(MyVariable)>(3.14) << endl;
输出:
3
3
关于c++ - 如何使用 type_info 进行类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4972795/