【问题标题】:What does the typeid(var_name).name() function returns in C++?typeid(var_name).name() 函数在 C++ 中返回什么?
【发布时间】:2016-02-02 13:29:42
【问题描述】:

我使用了#include <typeinfo>头文件下的typeid(var).name()函数,我看到它只返回一个字符。

例如。

#include <iostream>
#include <typeinfo>
int main()
{
    std::cout << typeid(5).name() << std::endl;
    std::cout << typeid(5.8).name() << std::endl;
    return 0;
}

输出:

i
d

所以,它显然返回了字符。

现在我正在尝试另一个出现错误的程序:

type.cpp:8:46: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
     if(typeid((-1 + sqrt(1 - 8 * t)) / 2).name() == 'i')

程序是:

#include <math.h>
#include <iostream>
#include <typeinfo>

int main()
{
    int t;
    std::cin >> t;

    if(typeid((-1 + sqrt(1 - 8 * t)) / 2).name() == 'i')
        std::cout << "YES";
    else
        std::cout << "NO";

    return 0;
}

为什么会出现这个错误?

【问题讨论】:

标签: c++


【解决方案1】:

成员函数name 返回const char * 类型的指针,而您正试图将它与char 类型的对象进行比较,该对象由于整数提升被转换为int 类型。

if( typeid((-1+sqrt(1-8*t))/2).name() == 'i' )
                                         ^^^^
                                         char converted to int

所以编译器会报错。

您可以使用标头&lt;cstring&gt; 中声明的标准函数std::strcmp。例如

if( std::strcmp( typeid((-1+sqrt(1-8*t))/2).name(), "i" ) == 0 )

然而,函数name生成什么字符串是实现定义的。

【讨论】:

  • "但是由函数名生成什么字符串是实现定义的。"值得强调,我想!
【解决方案2】:

typeid 返回一个 std::type_info 对象,std::type_info::name 返回 const char*(一个指针)。如果这个const char* 指向一个包含一个字符和一个NUL 终止符的数组,它将以与单个char 相同的方式打印。

关键是,您不能将const char*char 进行比较。 c-style字符串(与c-style字符串)的comaring函数是std::strcmp

但是...这不是typeid 的用例。表达式的类型:

(-1 + sqrt(1 - 8 * t)) / 2)

在编译时是已知的,并且 not 在运行时根据其值改变。它将始终是float。请注意,您可以使用以下命令检查类型(在编译时):

std::is_integral<decltype((-1 + sqrt(1 - 8 * t)) / 2)>::value

decltype 中的表达式不需要计算(也不能)来获取表达式的类型。

但是,你基本上想要this

【讨论】:

  • 这很有帮助。我们如何在运行时检查表达式类型?
  • 这个std::is_integral&lt;decltype((-1 + sqrt(1 - 8 * t)) / 2)&gt;::value 将如何帮助我?
  • @Aryan 表达式的类型不依赖于它的值。您在这里的意思可能是检查float 的值是否有点接近整数。你应该看到this post
猜你喜欢
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 2012-07-03
  • 2015-01-18
  • 1970-01-01
  • 2018-09-03
  • 2012-12-04
  • 1970-01-01
相关资源
最近更新 更多