So I am writing a particle accelerator code for a c++ class, and Im having trouble with the initial class set up Im being asked to use. The professor wants us to use templates for the class, but when I try to implement them, I receive a number of errors. For instance:
#include <iostream>
#include <cmath>
using namespace std;
template <class Type>
class ThreeVector {
private:
Type mx;
Type my;
Type mz;
public:
ThreeVector();
ThreeVector(Type x=0, Type y=0, Type z=0);
};
ThreeVector<Type>::ThreeVector() {
Type mx=0;
Type my=0;
Type mz=0;
}
ThreeVector<T>::ThreeVector(Type x, Type y, Type z) {
mx=x;
my=y;
mz=z;
}
is part of my header file (the class is required to be in a header file). When I run my program (can provide if needed), it gives me the following errors:
ThreeVector.h:30:13: error: ‘Type’ was not declared in this scope
ThreeVector.h:30:17: error: template argument 1 is invalid
ThreeVector.h: In function ‘int ThreeVector()’: ThreeVector.h:30:32: error: ‘int ThreeVector()’ redeclared as different kind of symbol
ThreeVector.h:6:7: note: previous declaration ‘template class ThreeVector’
ThreeVector.h:31:2: error: ‘Type’ was not declared in this scope
ThreeVector.h:32:7: error: expected ‘;’ before ‘my’
ThreeVector.h:33:7: error: expected ‘;’ before ‘mz’
ThreeVector.h: At global scope: ThreeVector.h:35:13: error: ‘Type’ was not declared in this scope
These problems did not exist before I started using the template, i.e., if I explicitly define all variable types, my class works fine. So, Im not really sure what is wrong with my template definition? If anyone could help, Id be really appreciative.
Thanks!
template<class T>
in front of the methods declared outside the class. (Replace T with whatever specifier is inside the template arguments.) – phantomtemplate<...>
applies only to the immediately following declaration or definition. – chris