Thread: Implementation of template functions in .cpp?

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

    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
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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,229
    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, 07:34 AM
  3. using Template Functions
    By ashcan1979 in forum C++ Programming
    Replies: 3
    Last Post: 09-20-2006, 12:44 AM
  4. Replies: 4
    Last Post: 05-28-2002, 04:14 AM
  5. bug for static functions in template class
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-16-2001, 06:38 PM