Making class a template
I created a class that stores 'double' numbers in a vector with two methods - minimum() and sort(). I also overloaded >> operator(simplified version). I need to create a template of this class in order to have ints, doubles and so on. I think i better write both classes below to make it clear.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Samplet {
public:
Samplet(vector<double> vec)
: v(vec) {}
Samplet() {}
friend istream& operator >>(istream& is, Samplet& s);
void sort_data();
double minimum();
private:
vector <double> v;
int size;
};
double Samplet::minimum() {
sort_data();
double minVal = v.front();
return minVal;
}
void Samplet::sort_data() {
sort(v.begin(), v.end());
}
//Input stream overloading for Samplet objects.
istream& operator >>(istream& is, Samplet& s) {
vector<double> vec;
double x;
while(is >> x)
vec.push_back(x);
s = Samplet(vec);
return is;
}
int main() {
Samplet s;
cin >> s;
cout << s.minimum() << endl;
}
//This is a template version
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <typename T>
class Samplet {
public:
Samplet(vector<T> vec)
: v(vec) {
}
Samplet() {}
friend istream& operator >>(istream& is, Samplet<T>& s);
void sort_data();
T minimum();
private:
vector <T> v;
int size;
};
template <typename T>
T Samplet<T>::minimum() {
sort_data();
T minVal = v.front();
return minVal;
}
template <typename T>
void Samplet<T>::sort_data() {
sort(v.begin(), v.end());
}
//Input stream overloading for Samplet objects.
template <typename T>
istream& operator >>(istream& is, Samplet<T>& s) {
vector<T> vec;
T x;
while(is >> x)
vec.push_back(x);
s = Samplet <T>(vec);
return is;
}
int main() {
Samplet s;
cin >> s;
cout << s.minimum() << endl;
}
Now, the non-template class works fine. But when i am trying to compile a template version it would not.
I have tried several exercises on templates and they work fine and I think my problem lies with my overloaded operator>>. (I changed the code in operator overloaded method several times, but still no luck.
Does anyone know what am i doing wrong - am I missing here something?
Any help will be appriciated.
Alex

