CPP/DataType Converter

From ProgrammingExamples
< CPP
Revision as of 23:16, 7 July 2010 by FirstPerson (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
#include <iostream>
#include <sstream>
#include <string>
 
using std::string;
using std::cout;
using std::endl;
using std::stringstream;
 
struct ConversionError: std::exception{
	ConversionError(const std::string& from, 
					const std::string& to
					)
					: exception( ("Failed to Convert From [" + from + "] to [" + to + "]").c_str() ){}
};
 
template< typename ReturnType, typename InputType>
ReturnType convertTo(const InputType& input){
	std::stringstream strm;
	strm << input;
	ReturnType val = ReturnType();	
	if( (strm >> val).fail() ){
		throw ConversionError( typeid(InputType).name(), typeid(ReturnType).name());
	}
	return val;
}
 
//for illustration purposes
struct Coord{
	int x,y;
	Coord(): x(), y(){}
};
std::istream& operator <<(std::istream& i, const Coord& c){
	//for illustration purposes only, will cause the stream to fail when extracted
	return i;
}
 
int main(){	
	//regular conversion
	float f = convertTo<float>( string("123") + ".456" );
	string s = convertTo<string>(f) + "789";
 
	cout << f << endl;
	cout << s << endl;
 
	//Conversion Fail
	Coord c;
	try{
		int i = convertTo<int>(c);
		cout << i << endl;
	}
	catch(const ConversionError& e){ cout << e.what() << endl;}
	return 0;
}