Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. ATL / WTL / STL
  4. Basic doubt with Class template

Basic doubt with Class template

Scheduled Pinned Locked Moved ATL / WTL / STL
c++
22 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lost User

    hrishi321 wrote:

    but it shows linking errors

    That has nothing to do with whether your source is in a .h or .cpp file. Link errors occur when you have references to objects or methods which do not exist within your program.

    hrishi321 wrote:

    FOR SOME REASON , I DON'T WANT TO PUT THE METHOD'S DEFINITIONS IN .h FILE

    1. Please do not SHOUT, we can read in normal case perfectly well. 2. You can put your definitions anywhere you like. The only requirement is that the compiler can find them when it comes across a reference in the source code. For example a statement of the form:

    CThing thing = new CThing();

    requires a definition of CThing, and that definition must already exist in the compiler's dictionary, having been found either in an included .h file, or previously in the current source .cpp file.

    The best things in life are not things.

    H Offline
    H Offline
    hrishi321
    wrote on last edited by
    #7

    thanks a lot, for all the points. But i am sorry, I really didn't get my answer... so does it mean to say, that I can put my class(template) method definitions in .cpp file?? Regards, hrishi

    L 1 Reply Last reply
    0
    • H hrishi321

      thanks a lot, for all the points. But i am sorry, I really didn't get my answer... so does it mean to say, that I can put my class(template) method definitions in .cpp file?? Regards, hrishi

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #8

      hrishi321 wrote:

      does it mean to say, that I can put my class(template) method definitions in .cpp file?

      Yes; I thought I had explained this in my previous two answers; obviously my explanations need some work.

      The best things in life are not things.

      H 1 Reply Last reply
      0
      • H hrishi321

        thanks for ur reply.... ok, I have a class template with few methods....according to my knowledge, we have to put the definitions of all template-class-methods in .h files itself .....actually , FOR SOME REASON , I DON'T WANT TO PUT THE METHODS DEFINITIONS IN .h FILE.......i want to put them in .cpp file, just like other normal classes that we do......is it possible? if so, how?.... thanks in advance Hrishi

        A Offline
        A Offline
        Albert Holguin
        wrote on last edited by
        #9

        You don't have to put the definitions in the header, just the declarations. In header file:

        template class CMyTemplate
        {
        public:
        virtual void Method1(void*);
        };

        In cpp file:

        template void CMyTemplate::Method1(void*){}

        H 1 Reply Last reply
        0
        • A Albert Holguin

          You don't have to put the definitions in the header, just the declarations. In header file:

          template class CMyTemplate
          {
          public:
          virtual void Method1(void*);
          };

          In cpp file:

          template void CMyTemplate::Method1(void*){}

          H Offline
          H Offline
          hrishi321
          wrote on last edited by
          #10

          Hello again :) thanks for ur reply... yes, so say in this program, here is the problem i am facning... Now in the main function, if I try to create an object . .like CMyTemplate<int> objT; it gives me linking error error LNK2001: unresolved external symbol "public: virtual void __thiscall CMyTemplate<int>::Method1(void *)" (?Method1@?$CMyTemplate@H@@UAEXPAX@Z) waiting for your reply.. thanks hrishi

          L 1 Reply Last reply
          0
          • L Lost User

            hrishi321 wrote:

            does it mean to say, that I can put my class(template) method definitions in .cpp file?

            Yes; I thought I had explained this in my previous two answers; obviously my explanations need some work.

            The best things in life are not things.

            H Offline
            H Offline
            hrishi321
            wrote on last edited by
            #11

            Hello again :) thanks for your all reply...for the same doubt, if you don't mind, could you please have a look at the comments and reply below (Mr. Albert), since it has an clear cut example and my doubt. thanks in advance Hrishi

            1 Reply Last reply
            0
            • H hrishi321

              Hello again :) thanks for ur reply... yes, so say in this program, here is the problem i am facning... Now in the main function, if I try to create an object . .like CMyTemplate<int> objT; it gives me linking error error LNK2001: unresolved external symbol "public: virtual void __thiscall CMyTemplate<int>::Method1(void *)" (?Method1@?$CMyTemplate@H@@UAEXPAX@Z) waiting for your reply.. thanks hrishi

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #12

              Where is the code for Method1()? I find it rather difficult to understand why you are using templates when you seem not to have mastered the basics of classes yet.

              The best things in life are not things.

              H 1 Reply Last reply
              0
              • L Lost User

                Where is the code for Method1()? I find it rather difficult to understand why you are using templates when you seem not to have mastered the basics of classes yet.

                The best things in life are not things.

                H Offline
                H Offline
                hrishi321
                wrote on last edited by
                #13

                Code In xxx.h file ::>> -------------------------------------- template <class T> class CMyTemplate { public: virtual void Method1(T TDummy); }; Code in xxx.cpp file ::>> -------------------------------------- #include "xxx.h" template <class T> void CMyTemplate<T>::Method1(T TDummy) { TDummy = TDummy + 1; } Code in main function ::>> -------------------------------------- CMyTemplate<int> objT;

                L 1 Reply Last reply
                0
                • H hrishi321

                  Code In xxx.h file ::>> -------------------------------------- template <class T> class CMyTemplate { public: virtual void Method1(T TDummy); }; Code in xxx.cpp file ::>> -------------------------------------- #include "xxx.h" template <class T> void CMyTemplate<T>::Method1(T TDummy) { TDummy = TDummy + 1; } Code in main function ::>> -------------------------------------- CMyTemplate<int> objT;

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #14

                  I cannot see anything wrong with this, and I have copied it into a test program of my own and it compiles and links successfully. There must be something different in your implementation that you have not shown in your message. Also, please surround your code snippets with <pre> tags (use the code block button) so it shows more clearly, like this:

                  template void CMyTemplate::Method1(T TDummy)
                  {
                  TDummy = TDummy + 1;
                  }

                  The best things in life are not things.

                  H 1 Reply Last reply
                  0
                  • L Lost User

                    I cannot see anything wrong with this, and I have copied it into a test program of my own and it compiles and links successfully. There must be something different in your implementation that you have not shown in your message. Also, please surround your code snippets with <pre> tags (use the code block button) so it shows more clearly, like this:

                    template void CMyTemplate::Method1(T TDummy)
                    {
                    TDummy = TDummy + 1;
                    }

                    The best things in life are not things.

                    H Offline
                    H Offline
                    hrishi321
                    wrote on last edited by
                    #15

                    thanks for your reply and your suggestions, Oh, I am really unable to figure it out. And there is no difference as such in my implementation. FYI, the linking error which i am getting is..

                    TestProject.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall CMyTemplate<int>::Method1(int)" (?Method1@?$CMyTemplate@H@@UAEXH@Z)

                    modified on Thursday, July 7, 2011 10:35 PM

                    L 1 Reply Last reply
                    0
                    • H hrishi321

                      thanks for your reply and your suggestions, Oh, I am really unable to figure it out. And there is no difference as such in my implementation. FYI, the linking error which i am getting is..

                      TestProject.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall CMyTemplate<int>::Method1(int)" (?Method1@?$CMyTemplate@H@@UAEXH@Z)

                      modified on Thursday, July 7, 2011 10:35 PM

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #16

                      I have no idea what you are doing wrong, as you have not shown your code. Here is an implementation that works; just copy this code and paste into a single .cpp file and build it.

                      #include <iostream>

                      using namespace std;

                      template class CMyTemplate
                      {
                      public:
                      virtual void Method1(T& TDummy);
                      };

                      template void CMyTemplate::Method1(T& TDummy)
                      {
                      TDummy = TDummy + 1;
                      }

                      int wmain()
                      {
                      int zz = 25;
                      CMyTemplate objT;
                      objT.Method1(zz);
                      wcout << L"Value of the dummy: " << zz << endl;

                      return 0;
                      

                      }

                      The best things in life are not things.

                      H 1 Reply Last reply
                      0
                      • L Lost User

                        I have no idea what you are doing wrong, as you have not shown your code. Here is an implementation that works; just copy this code and paste into a single .cpp file and build it.

                        #include <iostream>

                        using namespace std;

                        template class CMyTemplate
                        {
                        public:
                        virtual void Method1(T& TDummy);
                        };

                        template void CMyTemplate::Method1(T& TDummy)
                        {
                        TDummy = TDummy + 1;
                        }

                        int wmain()
                        {
                        int zz = 25;
                        CMyTemplate objT;
                        objT.Method1(zz);
                        wcout << L"Value of the dummy: " << zz << endl;

                        return 0;
                        

                        }

                        The best things in life are not things.

                        H Offline
                        H Offline
                        hrishi321
                        wrote on last edited by
                        #17

                        I think there is a misunderstanding. Sorry if my words were not able to explain my doubt. If you please refer to my main-doubt

                        Could anyone please tell me, is there any way to separate the definition of the methods of a template class ,from header file to .cpp file.

                        The code which you have provided works absolutely fine, in just one file. Just that I wanted to know, if there is any way to separate the definitions of the method in an another .cpp file. (Just like a normal class where we declare in .h and implement in .cpp)

                        template <class T>
                        void CMyTemplate<T>::Method1(T& TDummy)
                        {
                        TDummy = TDummy + 1;
                        }

                        and the declaration in an separet .h file

                        template <class T>
                        class CMyTemplate
                        {
                        public:
                        virtual void Method1(T& TDummy);
                        };

                        thanks in advance hrishi

                        L O 2 Replies Last reply
                        0
                        • H hrishi321

                          I think there is a misunderstanding. Sorry if my words were not able to explain my doubt. If you please refer to my main-doubt

                          Could anyone please tell me, is there any way to separate the definition of the methods of a template class ,from header file to .cpp file.

                          The code which you have provided works absolutely fine, in just one file. Just that I wanted to know, if there is any way to separate the definitions of the method in an another .cpp file. (Just like a normal class where we declare in .h and implement in .cpp)

                          template <class T>
                          void CMyTemplate<T>::Method1(T& TDummy)
                          {
                          TDummy = TDummy + 1;
                          }

                          and the declaration in an separet .h file

                          template <class T>
                          class CMyTemplate
                          {
                          public:
                          virtual void Method1(T& TDummy);
                          };

                          thanks in advance hrishi

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #18

                          OK, I think I understand what you are asking. You can put the definition and the implementation into a single .cpp file, but it must all be in the same file - as was the case with my sample. You cannot put the definition into one .cpp file and the implementation into another, as the information required by the compiler must be available in one compilation unit. It is much simpler to follow the default and put your definitions into a .h file and your implementation into the .cpp file(s). Doing it this way means that you can split the implementation across multiple files, as long as each one includes the definitions.

                          The best things in life are not things.

                          1 Reply Last reply
                          0
                          • H hrishi321

                            Hello everyone Could anyone please tell me, is there any way to separate the definition of the methods of a template class ,from header file to .cpp file. I know the way, wherein, we define all the methods in a file( with extension other then .cpp), and include the file at the end of the header file of the template class. But this method looks no good, is there any clean and usual way just like other class. thanks in advance Hrishi

                            P Offline
                            P Offline
                            Paul M Watt
                            wrote on last edited by
                            #19

                            Templates behave a lot like inline functions. The entire implementation is required to be declared in the include file for the compiler to use it correctly. I believe you have described this method in your question, but I would like to start here, because it is the method I prefer if I dont want a single .h file implementation. I will use the file name Tmp.x for all of the examples, where x is the extension. 1) You declare all of your template classes and functions in your file Tmp.h . 2) Then implement all of the functions in a separate file with an extension such as Tmp.inl (inline). It is important that when the function definitions appear outside of the class definition, that you declare each function declaration with inline. Otherwise if you include this header file in multiple places, you will get linker errors for duplicate symbols. 3) At the bottom of Tmp.h and the line #include "Tmp.inl". The file implemented in step 2. If you prefer to have the file extension to still be .cpp, you can use that as well. You would follow all of the steps the same way, and include the .cpp file at the end of the .h file. The only difference, in your Visual Studio project, you will have to change the settings for the file so that it does not get compiled like the other .cpp files. It is already included in a header file. You cannot get around having the Template implementation available to the compiler when it sees the first usage of the template. Why? Because that is the point where the compiler generates the actual code from the template. Originally there was supposed to be a keyword "export" to allow the templates to be defined like regular classes, but that never became part of the standard, and therefore is not available. Hopefully this helps.

                            H 1 Reply Last reply
                            0
                            • P Paul M Watt

                              Templates behave a lot like inline functions. The entire implementation is required to be declared in the include file for the compiler to use it correctly. I believe you have described this method in your question, but I would like to start here, because it is the method I prefer if I dont want a single .h file implementation. I will use the file name Tmp.x for all of the examples, where x is the extension. 1) You declare all of your template classes and functions in your file Tmp.h . 2) Then implement all of the functions in a separate file with an extension such as Tmp.inl (inline). It is important that when the function definitions appear outside of the class definition, that you declare each function declaration with inline. Otherwise if you include this header file in multiple places, you will get linker errors for duplicate symbols. 3) At the bottom of Tmp.h and the line #include "Tmp.inl". The file implemented in step 2. If you prefer to have the file extension to still be .cpp, you can use that as well. You would follow all of the steps the same way, and include the .cpp file at the end of the .h file. The only difference, in your Visual Studio project, you will have to change the settings for the file so that it does not get compiled like the other .cpp files. It is already included in a header file. You cannot get around having the Template implementation available to the compiler when it sees the first usage of the template. Why? Because that is the point where the compiler generates the actual code from the template. Originally there was supposed to be a keyword "export" to allow the templates to be defined like regular classes, but that never became part of the standard, and therefore is not available. Hopefully this helps.

                              H Offline
                              H Offline
                              hrishi321
                              wrote on last edited by
                              #20

                              thanks a lot, it was really helpful :) hrishi

                              1 Reply Last reply
                              0
                              • H hrishi321

                                I think there is a misunderstanding. Sorry if my words were not able to explain my doubt. If you please refer to my main-doubt

                                Could anyone please tell me, is there any way to separate the definition of the methods of a template class ,from header file to .cpp file.

                                The code which you have provided works absolutely fine, in just one file. Just that I wanted to know, if there is any way to separate the definitions of the method in an another .cpp file. (Just like a normal class where we declare in .h and implement in .cpp)

                                template <class T>
                                void CMyTemplate<T>::Method1(T& TDummy)
                                {
                                TDummy = TDummy + 1;
                                }

                                and the declaration in an separet .h file

                                template <class T>
                                class CMyTemplate
                                {
                                public:
                                virtual void Method1(T& TDummy);
                                };

                                thanks in advance hrishi

                                O Offline
                                O Offline
                                Orjan Westin
                                wrote on last edited by
                                #21

                                If you are still looking for an answer, I posted an article explaining this just today. http://www.codeproject.com/Articles/236927/All-your-base64-are-different-to-us In short, there is a way, provided you know all template types you will be using. I'll copy the example I had in the article here:

                                -------------------------------------
                                -- In my_template.h file
                                ...
                                template
                                T my_temp_func(const T& t);


                                -- In my_template.cpp file

                                #include "my_template.h"

                                // Definition
                                template
                                T my_temp_func(const T& t)
                                {
                                return t;
                                }

                                // Instantiation declaration
                                int my_temp_func(const int& t);


                                -- In using_my_template.cpp
                                #include "my_template.h"
                                ...
                                int i = my_temp_func(4); // works
                                string s = my_temp_func("Abob"); // link error

                                In the example above, the declaration in the last line of my_template.cpp tells the compiler there’ll be a variant of the template function that uses int as template parameter. Okay, says the compiler, I’ll put an inline copy there. Since the generic definition is right there in the same compilation unit (ie my_template.cpp), this is something the compiler can do – it has all the information it needs. The result of that is that in the compiled file (probably called my_template.obj) there is now a function that has the signature int my_temp_func(const int& t). This is a fully defined specialisation of a template function, so to the linker it looks just like a normal function. However, the linker won’t be able to find a string specialisation, so this will generate a linker error. In

                                1 Reply Last reply
                                0
                                • H hrishi321

                                  Hello everyone Could anyone please tell me, is there any way to separate the definition of the methods of a template class ,from header file to .cpp file. I know the way, wherein, we define all the methods in a file( with extension other then .cpp), and include the file at the end of the header file of the template class. But this method looks no good, is there any clean and usual way just like other class. thanks in advance Hrishi

                                  B Offline
                                  B Offline
                                  Bram van Kampen
                                  wrote on last edited by
                                  #22

                                  Your basic problem appears to be to understand how Header Files, cpp Files, the Compiler and the Linker work. First the Compiler. The Compiler builds an Object File. This is a Binary representation of a cpp File. It containd the CPP Code you wrote, converted to machine code as well as a whole raft of information needed later. The Compiler contains a thing, called a Pre-Processor. It prepares your CPP file before actual compilation. Conceptually it produces a New Source File. It copies your file Line by Line. but if it finds a statement like #include "MyBeautifulHdr.h", it does not copy the include statement, but, instead writes the entire contents of "MyBeautifulHdr.h" at the location of the '#include' statement. When it encounters a #define FOO 1 statement, it undertakes to replace henceforth every future occurrence of 'FOO' with 1. It goes on like that at infinitum, and the final file offered to the compiler has all '#includes, #defines, #if's etc resolved. At that stage the compiler does not know ( and does not care) from what file what item came from, (except for error reporting). It just builds the Object File, (if it Can) if it cannot, you get an error. Each of the Object Files generated roughly correspond to the code you wrote in a cpp file. An extern declaration is a promise to the compiler that somewhere in an other file or library, an item of that specification exists. The Linker tries to build an executable out of all those object files. In doing so, it may also include Object files written by others, e.g. those written by Microsoft, which came with your compiler package. To make that process more efficient, multiple obj files can be gathered together into a library (.lib) file If the linker cannot find a named item, or, finds more than one, the linker will fail building the executable. Getting a Full understanding of how your tools work will answer your queery. regards, :)

                                  Bram van Kampen

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups