CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2008

    about template and multiple files projects.

    C++ requires that the declaration and definition of a template must be in the same file.
    Suppose we have the following scenario:
    class<int> obj1;
    bla bla .....
    class<int> obj2;
    bla bla ....
    when file1.cc and file2.cc are complied separately, each of them will contain a realization of a template for int. I wonder how the linker handle this situation. The linker will leave two realizations in the final code(which will increase the size of the final code) or it will only keep one realization(which seems more complicated)

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Seattle, WA

    Re: about template and multiple files projects.

    The linker is able to figure it out properly. However, FYI, C++0x introduces the "extern templates" capability which explicitly forces the compiler not to instantiate a template in a particular translation unit, and the linker will pull a definition from elsewhere if it exists. I believe Visual Studio and gcc both support this in their latest versions.

  3. #3
    Join Date
    Jun 2009

    Re: about template and multiple files projects.

    Quote Originally Posted by gshy View Post
    C++ requires that the declaration and definition of a template must be in the same file.
    Not exactly. To be more accurate, it requires for the full definition to be visible in all translation units using the template. Or to be even more precise, it requires the definition of whatever is used in the translation unit.

    This usually leads to designs where the header file contains the class definition, at the end of which, we include a ".inl" file, which will contain the definitions of all the functions.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.