0

Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?
Do template class member function implementations always have to go in the header file in C++?

Ive made some stupid mistake here but i cant see what.

this compiles:

//start of header.h
namespace ns
{
    class A
    {
    public:
        template <class t>t func();
    };
    template<class t> t A::func()
    {
        t a;
        return a;
    }
}
//end of header.h

//start of imp.cpp

//end of imp.cpp

but the following does not:

//start of header.h
namespace ns
{
    class A
    {
    public:
        template <class t>t func();
    };
}
//end of header.h




//start of imp.cpp
#include "header.h"
using namespace ns;

template<class t> t A::func()
{
    t a;
    return a;
}

//end of imp.cpp

the error is : error LNK2019: unresolved external symbol "public: int __thiscall ns::A::func(void)" (??$func@H@A@ns@@QAEHXZ) referenced in function _main

Community
  • 1
  • 1
Lauer
  • 517
  • 1
  • 6
  • 11

2 Answers2

2

Templates must be implemented in the header file since they cannot be compiled until they are instantiated.

See this answer: Why can templates only be implemented in the header file?

Community
  • 1
  • 1
Matt
  • 21,026
  • 18
  • 63
  • 115
1

You should read Storing C++ template function definitions in a .CPP file . There is other situation with template specialization - it is more like normal function (declaration in the .hpp , definition in the .cpp). If you want to have a specialization in the header you should remember to add inline (because of ODR).

http://en.wikipedia.org/wiki/One_Definition_Rule[ODR][1]

Community
  • 1
  • 1
CyberGuy
  • 2,783
  • 1
  • 21
  • 31