2

I'm new to full-time C++ programming so I'm trying to gain a better understanding of the nuances involved in various things.

I'm using templates inside a small project, mostly making up the code as I learn, and I'm coming across some things I'm not so sure about. Visual studio helped me generate (in my .cpp file from my .h file)code equivalent to this:

template<class T>
PriorityQueue<T>::ClimbDownHeap(const int currentNodeIndex)
{
}

template<class T>
PriorityQueue<T>::GetRightNodeIndex(const int currentNodeIndex)
{
}

I am under the impression though that this would be just as valid:

template <class T>
class PriorityQueue
{
public:   
    ClimbDownHeap(const int currentNodeIndex)
    {

    }
private:
    GetRightNodeIndex(const int currentNodeIndex)
    {
    }
};

I may be wrong in my understanding, but so far at least it would seem both would compile. Are there any significant differences between the two of these styles? I'd prefer the second because it is more clean and clear to me. What is the nuance between these?

NOTE: Typing this on a bumpy train so I apologize for formatting issues or if the code is not clear (I typed it from memory of what I tried; it is not exact).

Caboose
  • 453
  • 5
  • 16
  • 2
    Putting template definitions in a source file can have problems. You can read [this](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) question to learn more about it. – Weak to Enuma Elish Mar 10 '17 at 02:56
  • See [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Guillaume Racicot Mar 10 '17 at 03:50
  • 2
    I can recommend a talk from **CppCon 2016: Arthur O'Dwyer "Template Normal Programming"** [Part1](https://www.youtube.com/watch?v=vwrXHznaYLA) and [Part2](https://www.youtube.com/watch?v=VIz6xBvwYd8) – Michael Nastenko Mar 10 '17 at 06:55
  • @MichaelNastenko Thank you, I found those videos to be both useful and entertaining. I'd definitely recommend them to anybody looking to gain a better understanding of templates. – Caboose Mar 15 '17 at 02:36

1 Answers1

1

Your template code must be put in the header if you want to use the template class from other files. Putting in source file effectively makes it private (by making linking impossible).

As James mentions in comment, read the detailed explanation and examples here.

Community
  • 1
  • 1
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41
  • If I'm reading those answers correctly, and I don't think I am, does that mean the most simple solution is to define all of the bodies in the .h file and possibly just do away with the .cpp? This is a far cry more difficult to grasp than generics in Java or C#, but I think I see, at least, the conceptual differences and performance implications. – Caboose Mar 10 '17 at 03:24