function pointer: 直接把function赋值给一个variable,这个variable()
就调用那个function;能这样做是因为compile之后function就是一堆bytecode instructions, 所以能赋值这堆instructions开始的address给一个变量variable
简单用法:类型直接用auto
:
void helloworld() {
std::cout << "hello world" << std::endl;
}
int main() {
auto function = helloworld;
function();
std::cin.get();
}
auto
, 被隐藏的类型是void(*f)()
, 实际上是void(*)()
:
-
void
对应function的返回值类型、 -
(*)
表明这是个pointer, - 最后的
()
表明是一个function, 其中可以按照正常的passing param传递参数
if hover: type: void(*)()
would be shown:
显式声明f
,是因为function pointer本身需要一个name:
void helloworld() {
std::cout << "hello world" << std::endl;
}
int main() {
void(*f)();
f = helloworld;
f();
std::cin.get();
}
或者并不显示声明,而只是typedef
, 那么后面就可以用这个类型(recommended):
void helloworld() {
std::cout << "hello world" << std::endl;
}
int main() {
typedef void(*HelloWorldFunction)();
HelloWorldFunction function = helloworld;
function();
std::cin.get();
}
增加一个参数 e.g.
void helloworld(int a) {
std::cout << "hello world" << a << std::endl;
}
int main() {
typedef void(*HelloWorldFunction)(int);
HelloWorldFunction function = helloworld;
function(7);
std::cin.get();
}
More practical e.g. (printEle
can vary a lot):
void printEle(int v) {
std::cout << "Value: " << v << std::endl;
}
void foreach(const std::vector<int>& nums, void(*func)(int)){
for (int num: nums) func(num);
}
int main() {
std::vector<int> nums = {1, 5, 4, 2, 3};
foreach(nums, printEle);
}
printEle
函数这个地方可以非常复杂:这也是真实用function pointer的地方;实际上如果只是print的情况下,可以直接用lambda表达式而不用定义一个function:
void foreach(const std::vector<int>& nums, void(*func)(int)){
for (int num: nums) func(num);
}
int main() {
std::vector<int> nums = {1, 5, 4, 2, 3};
foreach(nums, [](int v){std::cout << "Value: "<< v << std::endl;});
}