C++利用函数指针实现函数式编程的方法

2018-03-02  本文已影响91人  DarkBubble

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");
  }
}
// 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是一个一元函数,将参数作为原输入函数的第二个参数,并且求值返回。

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) 
}

使用成员函数,也是为了实现类似部分绑定,部分被绑定的参数作为类实例(对象)的其他成员。

上一篇 下一篇

猜你喜欢

热点阅读