Passing datatype into a function
Oct 7, 2012 at 3:29pm UTC
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 ...
Oct 7, 2012 at 3:38pm UTC
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 Oct 7, 2012 at 3:38pm UTC
Oct 7, 2012 at 3:40pm UTC
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" );
}
Oct 7, 2012 at 3:41pm UTC
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.
Oct 7, 2012 at 5:47pm UTC
thanks all ..I have used the function as used by both @vlad and @peter.
It works.
Topic archived. No new replies allowed.