Technique 1 -> Results in error
I have three files MyType.h
, MyType.cpp
& main.cpp
MyType.h
#ifndef MYTYPE_H
#define MYTYPE_H
#include<iostream>
using namespace std;
template <class T,int iMax>
class A{
T iData;
public:
void vSetData(T iPar1);
void vDisplayData();
};
#endif
MyType.cpp
#include"MyType.h"
void A::vSetData(T iPar1){
if(iPar1 <= iMax)
iData = iPar1;
}
void A::vDisplayData(){
cout<<"\nData is: "<<iData<<endl;
}
main.cpp
#include"MyType.h"
typedef A<int,20> MyType;
int main(){
int x = 12;
MyType obj;
obj.vSetData(12);
obj.vDisplayData();
return 0;
}
ERRORS: 10 errors. They are as follows:-
- mytype.cpp(2) : error C2955: 'A' : use of class template requires template argument list
- mytype.h(9) : see declaration of 'A'
- mytype.cpp(2) : error C2955: 'A' : use of class template requires template argument list
- mytype.h(9) : see declaration of 'A'
- mytype.cpp(2) : error C2065: 'T' : undeclared identifier
- mytype.cpp(2) : error C2146: syntax error : missing ')' before identifier 'iPar1'
- mytype.cpp(2) : error C2761: 'void A::vSetData(T)' : member function redeclaration not allowed
- mytype.cpp(2) : error C2059: syntax error : ')'
- mytype.cpp(2) : error C2143: syntax error : missing ';' before '{'
- mytype.cpp(2) : error C2447: '{' : missing function header (old-style formal list?)
- mytype.cpp(6) : error C2955: 'A' : use of class template requires template argument list
- mytype.h(9) : see declaration of 'A'
- mytype.cpp(6) : error C2509: 'vDisplayData' : member function not declared in 'A'
- mytype.h(9) : see declaration of 'A
Technique 2 -> Works fine.
AboveCodeInOneFile.cpp
#include<iostream>
using namespace std;
template <class T,int iMax>
class A{
T iData;
public:
void vSetData(T iPar1){
if(iPar1 <= iMax)
iData = iPar1;
}
void vDisplayData(){
cout<<"\nData is: "<<iData<<endl;
}
};
typedef A<int,20> MyType;
int main(){
int x = 12;
MyType obj;
obj.vSetData(12);
obj.vDisplayData();
return 0;
}
Please let me know what mistake i am doing in Technique 1