網頁

2017年4月15日 星期六

[C++] Any input type template function

主題 : Any input type template function

引言 : C++ 11 引入了此功能,讓 function 可以吃同類型任何型態的參數進來,並且還保持原來 type 的樣子。

描述 :
這名字我亂取的,我只是想要說明這樣的 pattern 的寫法可以讓你寫出一個 template function 可以吃所有同類型的 TYPE, TYPE&, TYPE&& ...

這真的很強大,不必再 for reference input 寫一個 function,for right value input 再寫一個 function。

已經有文章寫得很好了,請參照
http://thbecker.net/articles/rvalue_references/section_01.html
~
http://thbecker.net/articles/rvalue_references/section_08.html

一句話解釋,"當你想把 type 忠實的傳入到 func 內使用請使用以下的 pattern"
細節請讀 section_01~section_08

以下是 section_01~section_08 給的 factory design pattern 的範例,
這個 factory template function 的 arg 可能吃 1. value 2. reference 3. right value ...
因為 C++ 很在意 type,type 不對就 compile error
那我們要怎麼寫一個任何 type 都能傳入的 function 呢 ? 如下 function,


template<typename T, typename Arg> 
shared_ptr<T> factory(Arg&& arg)
{ 
  return shared_ptr<T>(new T(std::forward<Arg>(arg)));
} 

當 Arg 是 X 則 new T(X)
當 Arg 是 X& 則 new T(X&)
當 Arg 是 X&& 則 new T(X&&)

很神奇吧,我的說明肯定不會比 section_01~section_08 還好。
如果你想知道為什麼,耐著性子看完你就會知道為什麼了。

沒有留言:

張貼留言