I have defined template class in .h file, it includes defining a constructor having ostream class. I don't knot how use the constructor in main.
originally, I want to have summation of the ASCII codes of the stream from input, I need to to it with template class, instead of writing it for each type of variables.
.h file
#ifndef SPYOUTPUT_H
#define SPYOUTPUT_H
#include <iostream>
using namespace std;
template <class T>
class SpyOutput {
int Count, CheckSum;
ostream* spy;
public:
int getCheckSum();
int getCount();
~SpyOutput();
SpyOutput(ostream* a);
SpyOutput & operator << (T val);
}
#endif
.cpp
template <class T>
SpyOutput<T>::SpyOutput(std::ostream* a) {
spy = a;
Count = 0;
CheckSum = 0;
}
template <class T> SpyOutput<T>::~SpyOutput() {}
template <class T> SpyOutput<> & SpyOutput<T>::operator << (T val) {
stringstream ss;
ss << val;
string s;
s = ss.str();
*spy << s;
Count += s.size();
for (unsigned int i = 0; i < s.size(); i++) {
CheckSum += s[i];
}
return *this;
}
template <class T>
int SpyOutput<T>::getCheckSum() {
return CheckSum;
}
template <class T>
int SpyOutput<T>::getCount() {
return Count;
}
main.cpp
#include "SpyOutput.h"
#include <iostream>
#define endl '\n'
int main()
{
double d1 = 12.3;
int i1 = 45;
SpyOutput spy(&cout); // error agrument list of class template is missing
/*
template <class T> SpyOutput<T> spy(&cout); // not working error
SpyOutput<ostream> spy(&cout);
// not working error having error on operator <<not matches with these oprands
*/
spy << "abc" << endl;
spy << "d1=" << d1 << " i1=" << i1 << 'z' << endl;
cout << "count=" << spy.getCount() << endl;
cout << "Check Sum=" << spy.getCheckSum() << endl;
return 0;
}