本文介绍了传递函数的值(?)而不是函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这之前被问过,但我找不到它。

Sorry if this has been asked before, but I was unable to find it.

因此,我试图教育自己关于模板和新的C ++ 11功能(主要是lambdas,我总是喜欢在其他语言)。

So im trying to educate myself about templates and the new C++11 features (mainly lambdas, something I always liked in other languages).

但在我的测试中,我来到一个我不知道它的工作,我试图理解它是如何工作,但不能计算出来。

But in my tests I came to something I had no idea it worked, and I'm trying to understand how it works but cant figure it out..

以下代码:

template <class Func>
void Test( Func callback ) {
    callback( 3 );
}

void Callback( int i ) {
    std::cout << i << std::endl;
}

int main( int argc, char** argv ) {
    Test( &Callback ); // this I was expecting to work, compiler will see its a pointer to a function
    Test( Callback ); // this also works, but how?!
    return 0;
}



如果我理解模板的工作原理,因为第一次调用 Test(& Callback); 我期望工作,因为编译器将看到模板接收到一个函数地址,并将假设参数应该是一个指针。

If I understand how templates work, basically they're a scheme for the compiler to know what to build, so the first call Test( &Callback ); I was expecting to work because the compiler will see the template receives a function address and will assume the arguments should be a pointer.

但是第二次调用是什么?假设模板是什么?

But what is the second call? What is the template assuming it is? A copy of a functio (if that even makes any sense)?

推荐答案

函数可隐式转换为指向自身的指针;这种转换几乎无处不在。 Test(Callback) Test(& Callback)完全相同。没有什么区别。在这两种情况下, Func 被推导为 void(*)(int)

A function is implicitly convertible to a pointer to itself; this conversion happens pretty much everywhere. Test(Callback) is exactly the same as Test(&Callback). There is no difference. In both cases, Func is deduced to be void(*)(int).

函数指针很奇怪。您可以在

Function pointers are weird. You can find out more about them in "Why do all these crazy function pointer definitions all work?"

这篇关于传递函数的值(?)而不是函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:39