I’m trying to create a simple template class in c++. I’ve been trying to compile the following but I only get a compile error. This is the code:
#include <stdlib.h>
#include <stdio.h>
template<int size>
class array {
public:
int len;
int data[size];
array(void) : len(size) {}
virtual ~array(void) {}
};
int main() {
array<3> a;
for (int i=0; i < a.len; ++i) {
a.data[i] = i;
printf("%d\n", a.data[i]);
}
return 0;
}
This is the error g++-4.2.1 is giving me:
Undefined symbols:
"__Unwind_Resume", referenced from:
_main in ccaYob9x.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
If we comment out the line for the destructor then the code compiles as it should and it gives me a list of the number 0, 1, 2.
What my ultimate goal is after understanding how template base classes work is to create specialized template classes. I want to create a multidimensional array but I wish to specialize it for the cases when the dimension is 1, 2, and 3. I mainly want to be able to overload the operator() for those cases. In any case, using a template class like this saves me the trouble of allocating memory dynamically when the dimensions are 1, 2, and 3. Does someone know how to change the code to allocate memory dynamically? Doing so will require you to define the destructor, which is the problem I’m currently facing.
EDIT:
I’m not familiar with template specialization. Does someone know how to make a specialized template when size=1, 2 and 3 to have static memory for data and by default to have dynamic memory?
EDIT 2:
It seems that I’m having trouble due to my g++ compiler. Does anyone see anything with with this:
g++ -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5666.3~6/src/configure --disable-checking --enable- werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple- darwin10 --with-gxx-include-dir=/include/c++/4.2.1
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5666) (dot 3)
EDIT 3:
There has got to be something wrong with my g++ version. I just tried it with g++4.0 in the same machine and with the macports version g++-mp-4.3 and it works fine. I guess it is time to upgrade to the next version. Thank you for your answers and hints.
Try this:
With g++ you will not have compiling errors. You can define specialized operator() for each different array sizes without problems, like constructor and destructor seams.