C++雜談(一) - std::bind 包裝函式
===
會看到std::bind,主要是之前在學習ROS2的時候,看到了一段範例程式碼:
```Clike=
timer_ = this->create_wall_timer(500ms, std::bind(&MinimalPublisher::timer_callback, this));
```
這段程式碼的意思是每500ms執行名為timer_callback的function
如果對於ROS2或是這段完整程式碼有興趣的
[傳送門 - ROS2 (一) - 建立第一個專案](https://hackmd.io/AiYYiXN9QMGXvz68JouiwA)
---
好了,接下來我們直接來看,本章的主要探討的程式碼:
```Clike
std::bind(&MinimalPublisher::timer_callback, this)
```
以下定義引用 [cppreference](https://en.cppreference.com/w/cpp/utility/functional/bind)
```Clike=
template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
(since C++11)
(until C++20)
template< class F, class... Args >
constexpr /*unspecified*/ bind( F&& f, Args&&... args );
(since C++20)
(2)
template< class R, class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
(since C++11)
(until C++20)
template< class R, class F, class... Args >
constexpr /*unspecified*/ bind( F&& f, Args&&... args );
(since C++20)
```
好了,我相信看了定義之後,應該還是很多人看不懂。沒關係,如果大家看定義就懂了,我就直接收筆了,哈哈。
---
為了瞭解std::bind,我找到了這篇 [文章](https://www.jyt0532.com/2017/01/08/bind/)
其中這個範例:
```Clike=
int add(int x, int y){
return x + y;
}
auto add12 = bind(add, 1, 2);
cout << add12() << endl; // print 3
```
完整程式碼:
```Clike=
#include <iostream>
// include bind function
#include <functional>
using namespace std;
// add function
int add(int x, int y){
return x + y;
}
int main()
{
auto add12 = bind(add, 1, 2);
cout << add12() << endl;
return 0;
}
```
所以,bind函式的用法簡單來說就是:
```Clike=
std::bind(函式位址 ,函式參數1, 函式參數2, ...);
```
也可以將一個函式,包裝成新的函式:
```Clike=
std::bind(函式位址 ,placeholders::_1, placeholders::_2, ..., placeholders::_N);
```
placeholders::_N表示佔位符。[參考](https://en.cppreference.com/w/cpp/utility/functional/placeholders)
舉個例子:
```Clike=
#include <iostream>
// include bind function
#include <functional>
using namespace std;
// add function
int add(int x, int y, int z){
return x*100 + y*10 + z ;
}
int main()
{
auto add12 = bind(add, std::placeholders::_1, std::placeholders::_2, 3);
cout << add12(1,2) << endl; // print 123
return 0;
}
```
上述例子中:
x => std::placeholders::_1
y => std::placeholders::_2
z => 3
而add12(1,2):
x => 1
y => 2
z => 3
---
如果把std::placeholders::_N 順序亂放的話會變成:
```Clike
#include <iostream>
// include bind function
#include <functional>
using namespace std;
// add function
int add(int x, int y, int z){
return x*100 + y*10 + z ;
}
int main()
{
auto add12 = bind(add, std::placeholders::_2, std::placeholders::_1, 3);
cout << add12(1,2) << endl; // print 213
return 0;
}
```
這時:
x => std::placeholders::_2
y => std::placeholders::_1
z => 3
而add12(1,2):
x => 2
y => 1
z => 3
變成了一個新的函式
---
本篇就介紹到這裡,謝謝收看~~