本文介绍了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: 1cout << *pr; // output: 1cout << &pr; // 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=)(num_args=0).显然,函数本身可以做任何你想做的事情,这只是为了证明使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 09:15