g ++“调用”函数无括号(不是f(),但f;)。为什么总是返回1? [英] g++ "Calling" function without parenthesis ( not f() but f; ). Why always returns 1?

查看:122
本文介绍了g ++“调用”函数无括号(不是f(),但f;)。为什么总是返回1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++(GNU GCC g ++)。 callingfunction without()
函数不工作,但编译成功。

c++ (GNU GCC g++ ). "Calling" function without () The function is not working, but compiles ok.

更令人惊讶的是,这样的代码总是返回1 ...

More surprisingly, such code always returns 1...

有什么解释吗?

我希望函数名称只是一个常规指针,但似乎有点不同。

I expected function name to be just a regular pointer, but seems it's a bit different...

I got 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

}

#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 c>。如果你把 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.

EDIT:

对于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 =< pr的地址)(num_args = 0)。函数本身可以做任何你想要的,这只是为了证明,使用C ++ 11的可变参数模板,你可以匹配任意arity的函数指针。这仍然不能用于重载的函数和函数模板,而不指定你想要的重载(通常通过转换)。

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆