How to declare a class template?

How to declare a class template? I tried, as seen below, but can't seem to get it to work. The error I get is explicit qualification in declaration of at line 4 c20. I'm just trying to make it so that when the constructor runs and takes the x/y the x and y can both be one of any data type.


1
2
3
4
5
6
7
Main.cpp

#include<iostream>
#include"EXAMPLE.h"
using namespace std;
int main()
{/*hopefully there will be code here when I make the template work */ return 1;}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef EXAMPLE_H
#define EXAMPLE_H

#include<iostream>
using namespace std;

template<class undef>
class newClass
{
    undef var1;
    undef var2;
    newClass(undef x, undef y);
};

#endif

1
2
3
4
5
6
7
8
9
10
#include<iostream>
#include"EXAMPLE.h"

newClass::newClass(undef x, undef y)
{
    newClass::var1 = x;
    newClass::var2 = y;
}

Last edited on
If you want to define a function of a template class outside that class you need to write that template before that function:
1
2
3
4
5
6
7
8
9
#include<iostream>
#include"EXAMPLE.h"

template<class undef>
newClass::newClass(undef x, undef y)
{
    newClass::var1 = x;
    newClass::var2 = y;
}


Note that you cannot put a definition of a template function/constructor in its own .cpp. The compiler will ignore it.
When the function is used within another .cpp the linker will complain that it doesn't exists (undefined reference).
Thus move everything related to the template to its header.
Topic archived. No new replies allowed.