C++支持函数式编程,虽然使用的较少,下面列出一些用法:
- 普通函数作为回调
普通函数作为输入参数的高阶函数 是最基本的函数式用法:
// file: func_def.h
int func1(int a, int b);
int func2(int a, int b);
// ...
// file: callback_example.cpp
#include "func_def.h"
#include <map>
#include <iostream>
#include <exception>
// callback func1/func2 by name "func1" and "func2"
void callback(const std::string& name, int p1, int p2)
{
typedef std::string string;
typedef int (*func_t)(int,int);
static std::map<string, func_t> funcmap;
if(funcmap.find(name)!=funcmap.end())
{
return (funcmap[name])(p1,p2);
}else
{
throw std::exception("function_not_found");
}
}
- 部分函数的实现
利用struct
用来模拟绑定部分参数,实现类似部分函数(partial function)调用,这里我们定义一个struct partial_apply
来实现函数和部分参数的动态绑定:
// file: partial_apply.
struct partial_apply
{
typedef int(*func_t)(int,int)
partial_apply(func_t _func_ptr, int _p1) : func_ptr(_func_ptr), p1(_p1) {}
int operator() (int p2) const { return (*func_ptr)(p1,p2); }
func_t func_ptr;
int p1;
};
// ...
// file: partial_apply_example.cpp
#include "func_def.h"
#include <iostream>
int apply_add1(int p)
{
partial_apply instance(func1, p); // func1 defined in file func_def.h
int ret[10];
for(int i=0; i<10;++i)
ret[i] = instance(1);
}
在这个例子里,struct partial_apply
的构造函数绑定了一个二元函数,和这个函数的第一个参数,而它的成员算符operator()(int)const
是一个一元函数,将参数作为原输入函数的第二个参数,并且求值返回。
- 成员函数指针的调用
C++可以调用成员函数指针,不过定义时需要加上成员函数所属类型的标识符,如下:
struct A
{
int func1(int p1, int p2);
int func2(int p1, int p2);
};
typedef int (A::*member_func_t)(int,int);
注意:调用成员函数指针时按如下方式:
void my_example()
{
A a, b;
A* ptr = &a;
// acquire the function pointer
A::member_func_t f1 = &A::func1;
A::member_func_t f2 = &A::func2;
// call by reference
(a.*f1)(1,2); // call a.func1(1,2)
(b.*f2)(2,3); // call b.func2(2,3)
// call by pointer
(ptr->*f1)(1,2); // call ptr->func1(1,2)
(ptr->*f2)(2,3); // call ptr->func2(2,3)
}
使用成员函数,也是为了实现类似部分绑定,部分被绑定的参数作为类实例(对象)的其他成员。