Caboose
Caboose

Reputation: 463

C++ Method definition with templates

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).

Upvotes: 2

Views: 88

Answers (1)

Tatsuyuki Ishi
Tatsuyuki Ishi

Reputation: 4031

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.

Upvotes: 1

Related Questions