template应该说既熟悉又陌生,目前的理解看来是更高一级的抽象。在做系统级的组件时候还是很有威力的。
template理解关键点在于template的instanciate的模式。
- 最懒原则:在instanciate的时候,遵循最小原则或者最懒原则,能不instanciate则不instanciate。像有一些函数的实现没有被用到,则不会生成,这是一个基本原则,在我们需要判断的时候可以基于这个来。
- 可以在link time instanciate,compile time instantication没问题,还有link time instanciation。
这里有一个例子就是virtual function,template里面也有virtual function,这种情况的处理是需要link time的处理来解决,书中给出一个解决方案是在第一个instanciation的文件中去生成virtual table,然后只生成这一个。可见linking势不可避免了。
使用export关键字可以做非include式的instanciate,这种情况下因为实现不可见,instanciate只是做了一个declaration,然后在通过linker去link到相应的实现,具体的实现应该是compile结束后compiler给linker提出具体的需求,然后进行definition的生成。
其他一些不太熟悉的topic:
显示声明实例话template可以有效控制compile time。
explicit specialization definition很方便很有用。
partial specialization