通过引用或值传递函数

Passing function by reference or by value?

本文关键字:传递函数 引用      更新时间:2023-10-16
#include <iostream>
#include <algorithm>
using namespace std;
bool myfn(int i, int j) { return i<j; }

int main () {
int myints[] = {3,7,2,5,6,4,9};
 // using function myfn as comp:
cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl;
cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl;
return 0;
}

考虑到上面的代码,当我们尝试传递函子时,将myfn&myfn传递给min_element有什么区别吗?

通常,按引用传递和按值传递仅指传递变量,而不引用函数。(模板函数引入了一些复杂性,但这是另一个讨论。在这里,您将myfn作为指向函数的指针传递。如果您改用&myfn,则没有区别。编译器将隐式myfn转换为指向具有该名称的函数的指针。

如果我们把myfn

或&myfn传递给min_element有什么区别吗?

不。 无论如何,myfn都会隐式转换为指向函数的指针。所以根本没有区别。