c++ - 询问变量在 C++ 中是什么数据类型

标签 c++ variables type-conversion

我想知道你是否可以问一个变量在 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/

相关文章:

iphone - 为什么我不能在 Obj-C 中声明像 "newVariable"这样的变量?

C++:当我将值分配给缓冲区时,它不起作用

c# - 将 TimeSpan 数据类型转换为 DateTime?

c++ - 写入文件时遇到问题(ofstream)

c++ - 尝试开发一个程序来识别最小和最大的数字

mysql - 如何在不更改配置文件的情况下将 mysql character_set_database 设置为 utf8mb4?(因为我无权访问这些文件)

java - 在 Java 中将 C 的 uint32 转换为 int 的正确方法

c++ - gcc 4.7.1 构建以 undefined reference 结束

c++ - 使用另一个类的变量

c# - 哪一个更好? "var"还是 "DataType"?