Implementation of template functions in .cpp?

This is a discussion on Implementation of template functions in .cpp? within the C++ Programming forums, part of the General Programming Boards category; Is there a way to write the implementations of template functions (or methods of a template class) in .cpp? It's ...

  1. #1
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183

    Implementation of template functions in .cpp?

    Is there a way to write the implementations of template functions (or methods of a template class) in .cpp?

    It's making my header very ugly.

    If I just move them to .cpp, I get linker errors, as expected.

    Thanks

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,274
    Quote Originally Posted by cyberfish View Post
    Is there a way to write the implementations of template functions (or methods of a template class) in .cpp?
    The way I deal with this is to break the template header into two files, for instance Template.h and Template_impl.h, put the implementations in Template_impl.h, then include the implementation file at the end of the main header.

    In some cases I've seen people put the implementation in a .cpp and then include the .cpp from the main header. I'm guilty of it, but on the scale of evil it doesn't rank very high IMHO.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,303
    You can write the function template definition in a source file, then include that source file in the header. Another file extension, e.g., .ipp, would typically be used in order to avoid confusing such a "to be included" source file with one that is supposed to be compiled separately.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    Thanks.

    That sounds good.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. template functions?
    By ovid in forum C++ Programming
    Replies: 8
    Last Post: 02-25-2010, 09:15 AM
  2. Reference Counting
    By Dae in forum C++ Programming
    Replies: 10
    Last Post: 08-13-2009, 08:34 AM
  3. using Template Functions
    By ashcan1979 in forum C++ Programming
    Replies: 3
    Last Post: 09-20-2006, 01:44 AM
  4. Replies: 4
    Last Post: 05-28-2002, 05:14 AM
  5. bug for static functions in template class
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-16-2001, 07:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21