2013-10-15 21 views
0

我一直在研究boost :: bind和boost :: function。我可以提供一個示例更好地解釋我的理解..鑑於這種示例代碼段:在boost :: bind中指定參數佈局器後,爲什麼在調用它時會省略它?

void print(int x, int y){ 
    cout << x << "\t" << y << endl; 
} 

int main(){ 
     boost::function<void (int)> f = boost::bind (&print, _1, 2); 
    f(5); 
} 

顯示5 2。從我的理解,結合一個函數創建一個函數對象,可以有它的一些參數必然一些不變的參數(程序員的偏好)。

不過,我真的無法理解的是貼在下面的源代碼,這個代碼片段:

boost::function<void (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)> f = 
       boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1); 
interface->registerCallback (f); 

的論點是砂礦_1。它不應該是f(arg)嗎?爲什麼省略了arg?

  #include <pcl/io/openni_grabber.h> 
     #include <pcl/visualization/cloud_viewer.h> 

     class SimpleOpenNIViewer 
     { 
      public: 
      SimpleOpenNIViewer() : viewer ("PCL OpenNI Viewer") {} 

      void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &cloud) 
      { 
       if (!viewer.wasStopped()) 
       viewer.showCloud (cloud); 
      } 

      void run() 
      { 
       pcl::Grabber* interface = new pcl::OpenNIGrabber(); 

       boost::function<void (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)> f = 
       boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1); 

       interface->registerCallback (f); 

       interface->start(); 

       while (!viewer.wasStopped()) 
       { 
       boost::this_thread::sleep (boost::posix_time::seconds (1)); 
       } 

       interface->stop(); 
      } 

      pcl::visualization::CloudViewer viewer; 
     }; 

     int main() 
     { 
      SimpleOpenNIViewer v; 
      v.run(); 
      return 0; 
     } 
+1

你在問'registerCallback(f)'應該是'registerCallback(f(arg))'嗎? – 0x499602D2

+0

是的。還是有什麼我錯過了? :) – Xegara

+2

那麼,你正在註冊一個回調,而不是一個調用的結果。你註冊它的類將存儲它,並在稍後階段調用它。 – juanchopanza

回答

2

不,該函數並不試圖在registerCallback(f)上被調用。函數f正被傳遞給接受boost::function的參數。當稍後被調用時,參數將最終被賦予f。例如:

typedef boost::function<void (int)> Function; 

void h(Function f) 
{ 
    f(5); 
} 

int main() 
{ 
    auto cube = [] (int n) { std::cout << n * n * n; }; 

    h(cube); // cube is passed to the function, not called 
} 
相關問題