Is this the correct way to do this template?
I have a template I call StrmConvert, which uses std::stringstream to
convert from any type to any other type that can be used by stringstring.
This is what it looks like:
template<typename T, typename F > T StrmConvert( F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}
it works well for me, but I find it can be a lot of typing. I have it in a
namespace called jml so I wind up doing things like this:
std::cout << jml::StrmConvert<std::string>( floatvalue );
I find that 99% of the time I'm converting to std::string so I've decided to
specialize it (if that is the right term) this way:
template<typename F> std::string StrmConvert( F from )
{
return StrmConvert<std::string>( from );
}
and it seems to work. Now I can say:
std::cout << jml::StrmConvert( floatvalue );
because if I don't specify the typename T is uses the std::string. Is this
the right way to do it? It seems to work, but I want to know if there can
be any problems with this. I did this test and it works, I'm just a n00b
when it comes to templates.
#include <string>
#include <iostream>
#include <sstream>
template<typename T, typename F > T StrmConvert( F from )
{
std::stringstream temp;
temp << from;
T to = T();
temp >> to;
return to;
}
template<typename F> std::string StrmConvert( F from )
{
return StrmConvert<std::string>( from );
}
int main ()
{
std::cout << StrmConvert<std::string>( 123.45 ) << std::endl;
std::cout << StrmConvert( 123.45 ) << std::endl;
float MyValue = StrmConvert<float>( "123.456" );
std::cout << MyValue << std::endl;
std::string wait;
std::cin >> wait;
}