這兩個是 C++ 才有的東西,也是一般用 C++ 寫 project 常看到的東西
用途我就不多說了,直接進入重點:
1. inline
inline 簡單來說是個為了取代 C 的 Macro 而出現的東西
他具有 macro 的功能但是長得像 function
所以也會做 type checking
這也是一般會看到有人說最好用 inline 取代 Macro 的原因
但是 inline 並不是強制讓 compiler 做 inline 這件事
而是提示 compiler 試著去做,到底要不要做是由 compiler 決定
因此我在 nemo 的 code 中看到了大量的 inline...
但是這邊有個重點很容易被人忽略:
為了要讓 compiler 可以做 inline
整個 function definition 都要放在 header
不能只把 prototype 放在 header!!
這也是 nemo 會有 undefined reference 的原因所在
我個人的猜測是因為加上 inline 後 compiler 就不會把她當成一般的 function
如果做完 inline 後 compiler 就不會另外編出一個 function
所以在 link 時才找不到這個 function 而出現 undefined reference
2. template
template 的問題跟 inline 很像,也是一不小心會出現 undefined reference
template 中文一般是翻成模板,他會依據你 code 的情況在
"compile time"產生出那種 type 的 function/class
換言之 template 不會產生實體,只有當你真正用到她的時候才會有實體
(這個過程叫 instantiation)
另外一個大重點是他是在 compile time 產生的
所以你的 code 使用 template function/class 時
type 也必須要是在 compile time 就能決定的
(這也是一般為什麼使用到 template 的時候 compile time 會很久的原因
EX: STL or boost...)
因此接下來 template 常見的問題就是
分檔時把 template 的 declaration 跟 definition 分在 header 跟 source
結果 compile 時出現 undefined reference....
為何?
因為使用該 template 的是在另一個檔案
但是當你在 compile template definition 所在的檔案時
他不知道需要產生什麼 type 的 function/class
於是乎~他就不幫你產生囉~所以 link 時當然找不到
總結:
使用 inline 跟 template 的時候記得不要把 declaration 跟 definition 拆開!
(除非是 forward declaration)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.133.134.61