g ++“呼叫”没有括号的函数(不是f()但是f;)。为什么它总是返回1? [英] g++ "calling" a function without parenthesis (not f() but f; ). Why does it always return 1?
问题描述
函数不起作用,但编译成功。
更令人惊讶的是,代码总是返回1 ...
是否有解释?
我预计函数名称只是一个常规指针,但看起来有点不同......
我是否偶然得到所有1?
#include< iostream>
使用namespace std;
void pr()
{
cout<< 某物;
}
int main()
{
pr;
cout<< PR; //输出:1
cout<< * PR; //输出:1
cout<< &安培; PR; //输出:1
}
实际上,您并没有在代码中调用 pr
,而是将函数指针传递给 cout
。 pr
在传递给 cout $ c $>时会被转换为
bool
C>。如果你把 cout<< boolalpha
事先您将输出 true
,而不是 1
。
编辑:
使用C ++ 11,您可以编写以下重载:
模板< class RType,class ... ArgTypes>
std :: ostream&运算符<<(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的可变参数模板,你可以匹配任意参数的函数指针。这对于重载的函数和函数模板仍然不起作用,而没有指定你想要的重载(通常通过强制转换)。
In c++ (GNU GCC g++), my code is "calling" a function without (). The function is not working, but compiles ok.
More surprisingly, the code always returns 1...
Is there any explanation?
I expected the function name to be just a regular pointer, but seems it's a bit different...
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
}
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:
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) << ")";
}
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屋!