g++ quot;callingquot; a function without parenthesis (not f() but f; ). Why does it always return 1?(g++“调用;一个没有括号的函数(不是 f() 而是 f; ).为什么总是返回 1?)
问题描述
在 c++ (GNU GCC g++) 中,我的代码是调用"一个没有 () 的函数.该函数不工作,但编译正常.
In c++ (GNU GCC g++), my code is "calling" a function without (). The function is not working, but compiles ok.
更令人惊讶的是,代码总是返回 1...
More surprisingly, the code always returns 1...
有什么解释吗?
我希望函数名只是一个常规指针,但似乎有点不同......
I expected the function name to be just a regular pointer, but seems it's a bit different...
我得到全 1 只是偶然吗?
Did I get all 1's only by chance?
#include <iostream>
using namespace std;
void pr ()
{
cout << "sth";
}
int main()
{
pr;
cout << pr; // output: 1
cout << *pr; // output: 1
cout << ≺ // output: 1
}
推荐答案
您实际上并没有在代码中调用 pr,而是将函数指针传递给 cout.pr 然后在传递给 cout 时被转换为 bool.如果你把 cout <<boolalpha 事先你会输出 true 而不是 1.
You're not actually calling pr in your code, you're passing the function pointer to cout. pr is then being converted to a bool when being passed to cout. If you put cout << boolalpha beforehand you will output true instead of 1.
使用 C++11,您可以编写以下重载:
With C++11 you can write the following overload:
template <class RType, class ... ArgTypes>
std::ostream & operator<<(std::ostream & s, RType(*func)(ArgTypes...))
{
return s << "(func_ptr=" << (void*)func << ")(num_args="
<< sizeof...(ArgTypes) << ")";
}
表示调用cout <<pr 将打印 (func_ptr=.显然,函数本身可以做任何你想做的事情,这只是为了证明使用 C++11 的可变参数模板,你可以匹配任意数量的函数指针.如果没有指定您想要的重载(通常通过强制转换),这仍然不适用于重载函数和函数模板.
which means the call cout << pr will print (func_ptr=<address of pr>)(num_args=0). The function itself can do whatever you want obviously, this is just to demonstrate that with C++11's variadic templates, you can match function pointers of arbitrary arity. This still won't work for overloaded functions and function templates without specifying which overload you want (usually via a cast).
这篇关于g++“调用";一个没有括号的函数(不是 f() 而是 f; ).为什么总是返回 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:g++“调用";一个没有括号的函数(不是 f() 而
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
