How to reconcile the C++ idiom of separating header/source with templates? -
i'm wondering bit templating business.
in c , c++ common put declarations in header files , definitions in source files, , keep 2 separate. however, doesn't seem possible (in great way) when comes templates, , know, templates great tool.
also, boost headers, real issue. separating headers , source still idea in c++, or should not rely heavily on templates?
instantiating template costly @ compile time virtualy free @ runtime. basically, everytime use new template type, compiler has generate code new type, that's why code in header, compiler have access code later.
putting code in .cpp lets compiler compile code once speeds compilation. in theory write code in headers, work fine, take forever compile large projects. also, change 1 line anywhere, have rebuild everything.
now might ask, how comes stl , boost not slow? that's precompiled headers come rescue. pchs let compiler costly work once. works code won't change libraries, effect totally nullified code changes lot have recompile whole set of precompiled headers everytime. compiler use couple of tricks avoid recompiling template code in every compilation unit.
also note c++0x introduce explicit mechanisms better control template instantiation. able explicitly instantiate templates and, importantly, prevent instanciation in compilation units. however, of work being done compilers without our knowledge.
so, rule of thumb is, put code (and include directives) possible in .cpp. if can't, well, can't.
my advice be: don't template heck of it. if have template, careful , aware in fact choosing between speed of compilation , usability template bring.
Comments
Post a Comment