Boost.Program_options中的一个函数式编程的例子

    boost里的program_options提供程序员一种方便的命令行和配置文件进行程序选项设置的方法。
    其文档例子中有如下代码:
   
1  using   namespace  boost::program_options;
2  // 声明需要的选项
3  options_description desc( " Allowed options " );
4  desc.add_options()
5          ( " help,h " " produce help message " )
6          ( " person,p " , value < string > () -> default_value( " world " ),  " who " );

    看第4到6行,是不是感觉很怪?这种方式体现了函数式编程中最大的特点:函数是一类值,引用资料来说, 所谓“函数是一类值(First Class Value)”指的是函数和值是同等的概念,一个函数可以作为另外一个函数的参数,也可以作为值使用。如果函数可以作为一类值使用,那么我们就可以写出一些函数,使得这些函数接受其它函数作为参数并返回另外一个函数。比如定义了f和g两个函数,用compose(f,g)的风格就可以生成另外一个函数,使得这个函数执行f(g(x))的操作,则可称compose为高阶函数(Higher-order Function)。

    program_options里的这种方式是怎么实现的呢?通过分析boost的源代码,我们自己来写个类似的实现看看:
     test.h   
 1  #pragma once
 2 
 3  #include  < iostream >
 4  using   namespace  std;
 5 
 6  class  Test;
 7 
 8  class  Test_easy_init
 9  {
10  public :
11      Test_easy_init(Test *  owner):m_owner(owner){}
12 
13      Test_easy_init  &   operator  () ( const   char *  name);
14      Test_easy_init  &   operator  () ( const   char *  name, int  id);
15  private :
16      Test *  m_owner;
17  };
18 
19 
20  class  Test
21  {
22  public :
23       void  add( const   char *  name);
24       void  add( const   char *  name, int  id);
25 
26      Test_easy_init add_some();
27 
28  };

test.cpp
 1  #include  " test.h "
 2 
 3  Test_easy_init  &  Test_easy_init:: operator  () ( const   char *  name, int  id)
 4  {
 5 
 6      m_owner -> add(name,id);
 7       return   * this ;
 8  }
 9 
10 
11  Test_easy_init  &  Test_easy_init:: operator  () ( const   char *  name)
12  {
13 
14      m_owner -> add(name);
15       return   * this ;
16  }
17 
18  Test_easy_init Test::add_some()
19  {
20       return  Test_easy_init( this );
21  }
22 
23 
24  void  Test::add( const   char *  name)
25  {
26      cout << " add: " << name << endl;
27  }
28 
29  void  Test::add( const   char *  name, int  id)
30  {
31      cout << " add: " << name << " - " << id << endl;
32  }

使用方式:
1  Test t1;
2 
3  t1.add_some()
4      ( " hello " , 1 )
5      ( " no id " )
6      ( " hello2 " , 2 );

是不是很有意思。add_some()方法返回一个Test_easy_init类的对象,Test_easy_init类重载了操作符(),操作符()方法返回Test_easy_init类对象自身的引用。。

你可能感兴趣的:(Boost.Program_options中的一个函数式编程的例子)