c++ - `decltype(&ordenary_func)`和decltype`(ordenary_func)之间的区别

标签 c++ c++11 function-pointers implicit-conversion decltype

给定声明void close_file_func(std::FILE* fd){},我发现decltype(&close_file_func)void (*)(_IO_FILE*)的类型,而decltype(close_file_func)void (_IO_FILE*)的类型?

您可以通过https://godbolt.org/z/QK5q3o检查相关代码。

为了您的方便,我在下面发布了代码和执行输出。

#include<iostream>
#include<typeinfo>

void close_file_func(std::FILE* fd);

int main()
{
    std::cout << typeid(close_file_func).name() << std::endl;
    std::cout << typeid(&close_file_func).name() << std::endl;
}

//Terminate outputs:
//FvP8_IO_FILEE
//PFvP8_IO_FILEE
echo 'PFvP8_IO_FILEE' | c++filt -tvoid (*)(_IO_FILE*)
echo "FvP8_IO_FILEE" | c++filt -tvoid (_IO_FILE*)

这个表达式(std::cout << (close_file_func == &close_file_func) << std::endl;)是合法的。您看到close_file_func == &close_file_func返回true

我想了一遍又一遍,但我还是听不懂。对于这个问题的任何提示,我将不胜感激。

最佳答案

您可能会认为两者应该赋予与函数指针相同的类型。是的,function-to-pointer implicit conversion可能在某些上下文中执行1,但不是对decltype(close_file_func)(和typeid(close_file_func))执行。

当与实体一起使用时, decltype 将产生实体的类型。因此decltype(close_file_func)会准确产生函数类型,即void (_IO_FILE*)

1) If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity named by this expression.



另一方面&close_file_func接受函数的地址并返回函数指针,然后decltype(&close_file_func)产生函数指针类型,即void (*)(_IO_FILE*)

1对于 operator==

(强调我的)

In all cases, for the built-in operators, lhs and rhs must have either

  • arithmetic or enumeration type (see arithmetic comparison operators below)
  • pointer type (see pointer comparison operators below)

after the application of the lvalue-to-rvalue, array-to-pointer and function-to-pointer standard conversions.



函数到指针的隐式转换是在左操作数上执行的,因此close_file_func == &close_file_func正在比较函数指针。

关于c++ - `decltype(&ordenary_func)`和decltype`(ordenary_func)之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61996379/

相关文章:

c++ - cpp中的字符串比较

c++ - 'help' 编译器如何从作为函数的模板参数推导出函数模板返回类型?

c++ - 通过 T * 匹配 nullptr

c++ - 如何在不复制和保留 std::string 对象的情况下获得 C++ std::string char 数据的所有权?

C++ 函数指针类型与 Linux 和 VMS 上的候选不兼容

c++ - 如何在没有管理权限的情况下为我的应用程序实现自动更新

c++ - 使用 ifstream 将文件加载到字符串会加载另一个文件的不完整拷贝?

c++ - 通过隐式转换小于运算符?

c - 采访 : function pointers vs switch case

c - 套接字io函数send()和recv()的函数指针