我想知道你是否可以问一个变量在 C++ 中它是什么数据类型? 我也知道 Scheme,你只需做这样的事情:
(define x 5)
(number? x)
它会返回“真”。 在 C++ 中可以实现这样的功能吗?
最佳答案
C++ 等价物可能是这样的:
auto x = 5;
using x_type = decltype(x);
你可以检查它
if( std::is_same<x_type,int>::value ) ...
但我不确定这是您的想法,因为 C++ 是静态类型的。当你有一个类层次结构时,还有动态类型:
struct Base { virtual ~Base() {} };
struct Derived1 : Base {};
struct Derived2 : Base {};
int main()
{
Base* p = new Derived2;
if( dynamic_cast<Derived1*>(p) ) { /* is Derived1 */ }
else if( dynamic_cast<Derived2*>(p) ) { /* is Derived2 */ }
else { /* neither */ }
}
关于c++ - 询问变量在 C++ 中是什么数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19773453/