+ Reply to Thread
Results 1 to 2 of 2

Thread: Template example in C++ causes link time error, why?

  1. #1

    Template example in C++ causes link time error, why?

    Below template example in C++ causes link time error, why?

    Header file:
    Code:
    template <typename T>
    class MyFirstTemplate
    {
    private:
    	T m_T ;
    public:
    	MyFirstTemplate(T t) ;
    } ;
    Source file:
    Code:
    #include "Temp.h"
    
    template <typename T>
    class MyFirstTemplate::MyFirstTemplate(T t)
    {
    	m_T = t ;
    }
    Main source file:
    int main()
    {
    MyFirstTemplate<int> obj(1) ;
    return 0 ;
    }

    linker says:

    error LNK2001: unresolved external symbol "public: __thiscall MyFirstTemplate<int>::MyFirstTemplate<int>(int)" (??0?$MyFirstTemplate@H@@QAE@H@Z)

    What is the reason?

  2. #2
    The best way is to declare and define template class in header file and call it .hpp rather than .h!

    In your case:
    Code:
    template <typename T>
    class MyFirstTemplate
    {
    private:
    	T m_T ;
    public:
    	MyFirstTemplate(T t)
           {
    	     m_T = t ;
           }
    } ;

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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