Convert char* to abitrary numeric type without using stringstream
I'd like to be able to convert a char* to an arbitrary numeric type T Similar to below, but without using the stringstream library, and obviously that one uses the string type which I don't want to use either.
How would I go about doing this?
e.g.
template<class T>
T string_as_T( const string& s )
{
// Convert from a string to a T
// Type T must support >> operator
T t;
std::istringstream is开发者_开发知识库t(s);
ist >> t;
return t;
}
Traits?
template<class T>
char* fmt(T value) { throw new /*some exception, or return null*/; }
char* fmt<int>(int value) { return "%d"; } // forgive rusty specialization syntax
// write fmt<double>, char, float, long, etc
template<class T>
T string_as_T( const char* s )
{
T val;
sscanf(s, fmt(val), &val);
return val;
}
You can use boost.conversion, lexical_cast to achieve this.
#include "boost/lexical_cast.hpp"
char* string = "15";
int output = 0;
output = boost::lexical_cast<INT_TYPE>(string);
精彩评论