pointers - Difference between void(*)() and void(&)() in C++ -
this question has answer here:
- function pointer vs function reference 3 answers
in example code, func1
type of void (*)(int, double)
, funky
type of void(&)(int, double)
.
#include <iostream> using namespace std; void somefunc(int i, double j) { cout << << ":" << 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 difference:
pfvide fvide 10:20 10:30
practically, difference between 2 types?
if wanted able assign pointer function , later change pointer points use auto fp = func
. if not use reference auto& rp = func
since 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 trying come more practical example of why ever this, below code uses array of pointers call function based on user input (any element of arr
changed during run time point function):
#include <iostream> using namespace std; void funca(int i, int j) { std::cout << "0: " << << ", " << j << endl; } void funcb(int i, int j) { std::cout << "1: " << << ", " << j << endl; } void funcc(int i, int j) { std::cout << "2: " << << ", " << 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; }
Comments
Post a Comment