作者shininglion (lionking - 辛巴)
看板NCTU_CS_EDA
标题[心得] inline & template
时间Sun Mar 25 17:41:23 2012
这两个是 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