Examples
Team LiB
Previous Section Next Section

Examples

Some subtler issues arise in connection with templates.

Example 1: Dependent names. Templates are compiled at the point where they are defined, except that any dependent names or types are not compiled until the point where the template is instantiated. This means that a template<class T> class Widget with a std::deque<T> member does not incur a compile-time error even when <deque> is not included, as long as nobody instantiates Widget. Given that Widget exists in order to be instantiated, its header clearly should #include <deque>.

Example 2: Member function templates, and member functions of templates, are instantiated only if used. Suppose that Widget doesn't have a member of type std::deque<T>, but Widget's transmogrify member function uses a deque. Then Widget's callers can instantiate and use Widget just fine even if no one includes <deque>, as long as they don't use TRansmogrify. By default, the Widget header should still #include <deque> because it is necessary for at least some callers of Widget. In rare cases where an expensive header is being included for few rarely used functions of a template, consider refactoring those functions as nonmembers supplied in a separate header that does include the expensive one. (See Item 44.)

    Team LiB
    Previous Section Next Section