Difference between revisions of "CPP/Classes/Conversion Function"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(Created page with '<source lang = "cpp"> #include <iostream> #include <climits> #include <sstream> #include <string> using namespace std; template<typename R, typename T> R to(const T& in){ stri…')
 
(No difference)

Latest revision as of 13:29, 21 July 2010

#include <iostream>
#include <climits>
#include <sstream>
#include <string>
 
using namespace std;
 
template<typename R, typename T>
R to(const T& in){
	stringstream ss;
	ss << in;
	R r = R();
	ss >> r;
	return r;
}
 
class Int{
private:
	int var;
public:
	Int(int i = 0): var(i){};
 
	int value(){ return var; }
	void value(int i){ var = i; }
 
	//conversion operator
	operator string(){ return to<string>(var); }
};
 
int main(){	
	Int num = 10;
	string strNum = num; //use the conversion operator
	cout << num.value()  << endl;
	cout << strNum + ".456" << endl;
}