g++“调用";一个没有括号的函数(不是 f() 而是 f; ).为什么总是返回 1?

g++ quot;callingquot; a function without parenthesis (not f() but f; ). Why does it always return 1?(g++“调用;一个没有括号的函数(不是 f() 而是 f; ).为什么总是返回 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 << &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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)