about template and multiple files projects.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: about template and multiple files projects.

  1. #1
    Join Date
    Mar 2008
    Posts
    6

    about template and multiple files projects.

    Hello,
    C++ requires that the declaration and definition of a template must be in the same file.
    Suppose we have the following scenario:
    //tc.h
    template<T>
    class{
    };
    //file1.cc
    #include"tc.h"
    class<int> obj1;
    bla bla .....
    //file2.cc
    #include"tc.h"
    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
    Location
    Fairfax, VA
    Posts
    10,891

    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
    Location
    France
    Posts
    2,339

    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 LITE 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

This is a CodeGuru survey question.


Featured


HTML5 Development Center