3

Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?

My header file has

template <typename T>
class AA : public BB<T>
{
public:
    AA()
    { ... }

this is working fine. But I need to separate the constructor implementation from header file.

So in cpp, I have

template <typename T>
AA<T>::AA()
{ ... }

When I compile this, it compiled but I get unresolved external symbol error. What am I missing here?

Community
  • 1
  • 1
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240
  • Not recommended but you can go into your cpp and at the very end instantiate all possible templates like `AA a; AA c;` etc to resolve the link errors – parapura rajkumar Dec 29 '11 at 23:47
  • You'll need to shop for a compiler that uses the Edison Design Group front-end. The only guys that actually implemented external linkage on templates. It is deprecated in the current C++ standard. The most influential vote for the deprecation came from the Edison Design Group. – Hans Passant Dec 29 '11 at 23:48
  • @parapurarajkumar I am not sure I understand you correctly. – Tae-Sung Shin Dec 29 '11 at 23:50
  • @HansPassant OK. So this is not possible then. Thanks for the info. – Tae-Sung Shin Dec 29 '11 at 23:52
  • Sorry for the duplicate. I really tried to find old question though. – Tae-Sung Shin Dec 29 '11 at 23:55
  • 1
    @HansPassant: template names can (and usually) do have external linkage in the current C++ standard and that hasn't changed since the last standard. `export` and the concept of _exported_ templates, on the other hand has been removed (not deprecated) from C++11. – CB Bailey Dec 30 '11 at 00:44
  • 1
    @Paul : There's no real harm in posting a duplicate, as long as you don't take offense to the question being closed. :-] – ildjarn Dec 30 '11 at 00:45
  • 1
    Well, that's indeed the proper verbiage. But if *templates* had external linkage instead of template *instantiations* then it wouldn't be a universal problem. – Hans Passant Dec 30 '11 at 00:50

2 Answers2

6

You can explicitly instantiate templates in your implementation file using :

template class AA<int>;

this will generate a definition from a template, but it is of use only if you know what types your class clients will use

marcinj
  • 48,511
  • 9
  • 79
  • 100
2

If you put a template implementation into a .cpp file you need to make sure that it gets instantiated: the compiler won't do it automatically for you. Roughly the same question was answered about a day ago: do template always have to be in the header?

Community
  • 1
  • 1
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380