c++ - Template instantiation effect on compile duration -


writing template classes have inline method bodies in .h files (unless instantiating them in .cpp files). know modifying inlined method requires recompiling units included them. it'll make compiling long. technique implement template class instantiating in .cpp file.

file test.h:

template <typename t> class test { public:     t data;     void func(); }; 

file test.cpp:

template <typename t> void test<t>::func() { }  template class test<float>; // explicit instantiation 

well. technique effective reduce compilation time uses test<float> after modification on func()?

since definitions of member functions inside cpp , not available other translation units, functions won't implicitly instantiated , cost of compiling code limited single cpp.

the problem approach limiting use of template type (or types) provide manual instantiations. external users cannot instantiate other types, if have it, need remember manually specialize each type want use.

there alternative, more cost (not much), generic , faster compile naïve approach. can provide template definitions in header, instruct compiler not implicitly instantiate set of common types, provide manual instantiations in single translation unit:

// .h #ifndef test_h #define test_h template <typename t> class test { public:     t data;     void func() { ... }  // definition here }; extern template class test<float>;   // declare explicit instantiation float extern template class test<int>;     //                                int #endif /* test_h */  // cpp #include "test.h" template class test<float>;          // explicit instantiation template class test<int>; 

in approach template visible instantiations type user might want use. explicitly tell compiler not work known subset of types provide specializations. if user wants test<std::string> compiler instantiate implicitly, , translation unit pay price. translation units instantiate test<float>, test<int> or include header don't instantiate template @ all, there additional cost (the parser needs handle definitions) there won't generated code (binary), or time wasted on optimizer and/or linker discarding duplicate symbols.

it implies, mention, recompiling user code included header if contents of header change.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -