design - How to decide when to implement a C++ template? -


i'm coming c, , getting deeper , deeper c++. using container classes of standard library, as-well smart pointer classes boost library, i've had first introduction class templates. use them lot now.

recently made first approach of writing my own class templates. 99% of can think of, class template might useful, class template exists in standard library or 1 of boost libraries.

when decide implement class template? criteria? have example?

c++ proposes several programming paradigms, have discovered, , not exclusive.

what write templates written object-oriented codes, it's matter of trade-off.

the c++ templates follow generic programming paradigm, idea class / method able work type, long instances of type follow concept.

the first striking difference, regard object-oriented code, there no need common base class. in fact, combining templates , free-functions, can work heterogeneous set of objects.

that therefore when shine:

  • if have heterogeneous set of objects want work
  • if refactoring them not possible (for various reasons)

then using template seems idea.

generally speaking, i've created them either small utilities or frameworks. in "business" code use them, define new ones. example:

  • box::enum<typename enumtype> wraps enum proposes seamless conversion to/from string (useful pretty printing in logs), serialization , like
  • box::identifier<typename t> wraps integer (essentially) , allow me create hierarchy of identifiers types similar hierarchy of types, dummyobjectid can passed when 1 expect objectid, not other way around

in general, there therefore 2 situations in used templates:

  • preventing copy/pasting
  • increasing type safety

if find in 1 of those, perhaps think it.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -