Passing datatype into a function

Here is the sample code
1
2
3
4
5
6
template <typename T>
inline T fromString(const string &str , T &tx){
    istringstream stream(str) ;
    stream >> tx ;
    return tx ;
}


Instead of passing the variable , I want to pass the datatype into which the string should be converted. For example :
1
2
cout << fromString("12",int); // output : 12
cout << fromString('1',char); //output : 1 


Any suggestions will be appreciated. thanks ...
1
2
3
4
5
6
7
template <typename T>
inline T fromString(const string &str){
    istringstream stream(str) ;
    T tx;
    stream >> tx ;
    return tx ;
}


1
2
cout << fromString<int>("12"); // output : 12
cout << fromString<char>("1"); //output : 1  
Last edited on
You can try the following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <sstream>
#include <string>

template <typename T>
inline T fromString( const std::string &str )
{
    T tx ;
    std::istringstream stream( str ) ;
    stream >> tx ;
    return tx ;
}

int main()
{
   int x = fromString<int>( "12" );
}
I don't think you can pass a datatype. It seems that your code is correct above. It uses a template which passes as a parameter a type T, which is the return type.
thanks all ..I have used the function as used by both @vlad and @peter.
It works.
Topic archived. No new replies allowed.