Difference between void (*) () and void (&) () in C ++
In this code example, func1
is a type void (*)(int, double)
and funky
is a type void(&)(int, double)
.
#include <iostream>
using namespace std;
void someFunc(int i, double j) {
cout << i << ":" << j << endl;
}
int main(int argc, char *argv[]) {
auto func1 = someFunc;
auto& func2 = someFunc;
cout << typeid(func1).name() << endl;
cout << typeid(func2).name() << endl;
func1(10, 20.0);
func2(10, 30.0);
}
The output shows the difference:
PFvidE
FvidE
10:20
10:30
In practice, what is the difference between the two types?
source to share
If you want to be able to assign a pointer to a function and then change what that pointer points to, use auto fp = func
. If not, use a link auto& rp = func
as you cannot reassign it:
#include <iostream>
using namespace std;
int funcA(int i, int j) {
return i+j;
}
int funcB(int i, int j) {
return i*j;
}
int main(int argc, char *argv[]) {
auto fp = funcA;
auto& rp = funcA;
cout << fp(1, 2) << endl; // 3 (1 + 2)
cout << rp(1, 2) << endl; // 3 (1 + 2)
fp = funcB;
//rp = funcB; // error: assignment of read-only reference 'rp'
cout << fp(1, 2) << endl; // 2 (1 * 2)
return 0;
}
I was trying to come up with a more practical example of why anyone has ever done this, below is the code that uses an array of pointers to call a function based on user input (any element arr
can also be changed at runtime to point to another function) :
#include <iostream>
using namespace std;
void funcA(int i, int j) {
std::cout << "0: " << i << ", " << j << endl;
}
void funcB(int i, int j) {
std::cout << "1: " << i << ", " << j << endl;
}
void funcC(int i, int j) {
std::cout << "2: " << i << ", " << j << endl;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
cout << "Usage: ./a.out <val>" << endl;
exit(0);
}
int index = atoi(argv[1]);
if (index < 0 || index > 2) {
cout << "Out of bounds" << endl;
exit(0);
}
void(* arr[])(int, int) = { funcA, funcB, funcC };
arr[index](1, 2);
return 0;
}
source to share
auto func1 = someFunc;
auto& func2 = someFunc;
Let's say you have another function and you want func2 to point to this other function
void function()
{
cout<<"Hello world"<<endl;
}
So you do below
func2 = function();
All you get is a compilation error. The reason func2
is a link and once the link is initialized it cannot be changed.
source to share