Templed classes and static methods

Started by
2 comments, last by GameDev.net 18 years, 1 month ago
Hello. I'm trying to write a heapsort for my class. So far, I have a working templated Heap class. To this, I added two static methods:
static Heap BuildHeap(Type list[], int numItems)
{
	Heap ret;
	ret.size = numItems;
	ret.capacity = numItems;
	ret.array = list;
	int index = ParentOf(ret.size - 1);
	while (index >= 0)
	{
		ret.WalkDown(index);
		index--;
	}
}
static void Sort(Type list[], int numItems)
{
	Heap<Type> heap;
	heap = Heap.BuildHeap(list, numItems);
	heap.Print();
	// Remove max the items into order
}
The goal is to be able to call the Sort method as
Heap.Sort(array, sizeofArray)
to sort the list. However, since Heap is a templated class, Sort incorporates the dynamic type Type, and gives me errors when trying to compile my main:
#include <iostream>
#include <stdlib.h>
#include "heapsort.h"

using namespace std;

int main()
{
        int array[] = {11, 22, 43, 45, 33, 23, 43};

        Heap.Sort<int>(array, 7);
}
Removing the <int> doesn't help any. However, if I comment out the call to Heap.Sort, it compiles just fine. Anyhelp would be appreciated.
Advertisement
There are a couple things wrong.
  1. The syntax is wrong. You can't do type.member. You have to do type::member or object.member
  2. The template parameters need to go with the templated thing. In your case, Heap is templated, not the function.
Try
    Heap<int>::Sort( array, 7 ); 
Also "Heap::Sort(array, 7);" won't work because the compiler won't deduce the class's template parameters from the function's parameters.

Edit: typo

[Edited by - JohnBolton on March 5, 2006 10:05:51 PM]
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
EDIT: Beaten by JohnBolton. Post trimmed to not overlap.

In the future, allways post error messages. If the above does not fix all your problems, please post said messages.

As an aside, when programming in C++, one should use the C++ versions of C library headers.

Instead of:

#include <stdlib.h>

Use:

#include <cstdlib>

This will also cause the functions in that header to be found within the std:: namespace.
Quote:Original post by JohnBolton
There are a couple things wrong. The syntax is wrong. You can do type.member. You have to do type::member or object.memberThe template parameters need to go with the templated thing. In your case, Heap is templated, not the function.Try Heap<int>::Sort( array, 7 ); Also "Heap::Sort(array, 7);" won't work because the compiler won't deduce the class's template parameters from the function's parameters.


Whoa. I've been programming in Java for too long. Thanks. I should have realized that.

This topic is closed to new replies.

Advertisement