Hi. I have encountered a problem with template class.
I have made a template class that converts a value into a string, and then made another template class that converts string to T if its possible. Now I need to overload >> and << operators for type T. I am kind of lost here. Would anyone please help?
template<typename T>
string toString (const T &value) // convert a value into a string
{
ostringstream os;
//os << value;
return os.str();
};
template <typename T>
T toValue(const string &str )
{
istringstream is(str);
T retValue;
// If it's possible to convert the string to T
if ( is >> retValue )
return retValue; // return the result
// Else return the default value of T
return T();
};
int main()
{
//const char c[]="John:Warren:364879:4.55"; // I want to display this, but it does not work
int num = 364879;
string str = toString(num);
int i = toValue<int> (str);
cout << i << endl;
double dNum = 4.55;
string str2 = toString(dNum);
double d = toValue<double> (str2);
cout << d << endl;
return 0;
}
// If it's possible to convert the string to T
if ( is >> retValue )
return retValue; // return the result
// Else return the default value of T
return T();
That won't work. If there is no istream& opeartor>>(istream&, T&) function, this will just fail to compile. SFINAE is not invoked. SFINAE is only invoked on the function signature, not from the function's contents. And even if it did, the function toValue() would just disappear.
You should be able to do it using SFINAE using one of the methods stated here:
As for overloading the >> and << operators, you just overload them. Define a function with the signature ostream& operator<<(ostream& os, your_type_here const & obj);. Similarly for >> and istream. However, you can't just overload for any T. You would have some constraints on T to be able to do anything useful. Since this is a non-member function, you need to declare it as a friend to the class it is referring to or you will not be able to get access to the non-public members.