C++:如何将函数引用传递给另一个函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7142883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:31:19  来源:igfitidea点击:

C++:How to pass reference-to-function into another function?

c++functionpass-by-referenceargument-passing

提问by Hudson Worden

I have been reading about function pointers and about using them as parameters for other functions. My question is how would you pass a function by reference without using pointers? I have been trying to find the answer on the Internet but I haven't found a good answer. I know that you can pass variables by reference like this: void funct(int& anInt);. How would you do something similar to this but instead of a reference to a variable a reference to a function was the parameter? Also how would you use a reference to the function in a function body?

我一直在阅读有关函数指针以及将它们用作其他函数的参数的信息。我的问题是如何在不使用指针的情况下通过引用传递函数?我一直试图在互联网上找到答案,但我还没有找到好的答案。我知道,你可以通过这样的引用传递变量: void funct(int& anInt);。你会如何做类似的事情,但不是对变量的引用,而是对函数的引用是参数?另外,您将如何在函数体中使用对函数的引用?

回答by Cheers and hth. - Alf

#include <iostream>
using namespace std;

void doCall( void (&f)(int) )
{
    f( 42 );
}

void foo( int x )
{
    cout << "The answer might be " << x << "." << endl;
}

int main()
{
    doCall( foo );
}

Cheers & hth.,

干杯 & hth.,