给定声明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 -t
说void (*)(_IO_FILE*)
,echo "FvP8_IO_FILEE" | c++filt -t
说void (_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/