Class Templates

I would like to convert a value into a string, and extract a value from a string.
And then call these functions in the main.

template<class T>
string toString (T value) // convert a value into a string
{
stringstream ss;
ss << value;
return ss.str();
};

template <class T>
T toValue(string str) // extract the value from a string
{
stringstream ss;
ss >> str;
return ss.str();
};

Are above functions correct? And how should I call in main? Please help me!

int main()
{
const int SIZE=10;
toString<int> intValue(SIZE); //seems not right
toString<double> doubleValue(SIZE); // seems not right
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <sstream>

template < typename T > std::string to_string( const T& value )
{
    std::ostringstream os ;
    os << value ;
    return os.str() ;
}

template < typename T > T to_value( const std::string& str )
{
    std::istringstream is(str) ;
    T value ;
    if( is >> value >> std::ws && is.eof() ) // success
        return value ;
    else // failed
       // report error (throw something)
       return T() ;
}

int main()
{
     int i = 12345 ;
     std::string str = to_string(i) ;
     int j = to_value<int>(str) ;
     std::cout << "i: " << i << " str: " << str << " j: " << j << '\n' ;

     double d = 123.45 ;
     str = to_string(d) ;
     double e = to_value<double>(str) ;
     std::cout << "d: " << d << " str: " << str << " e: " << e << '\n' ;
}

http://ideone.com/FUzMOy
toString is correct, toValue should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <class T>
T toValue( string str )
{
    stringstream ss;
    ss << str;

    T retValue;

    // If it's possible to convert the string to T
    if ( ss >> retValue )
    {
        // return the result
        return retValue;
    }

    // Else return the default value of T
    return T();
}


Then in main() you can call them like this:
1
2
3
4
string str = "1234";
int value = toValue < int > ( str ); // value now holds 1234

string str2 = toString( value ); // str2 now holds "1234" 
Last edited on
Thank you very much guys. I appreciate it.
Topic archived. No new replies allowed.