0

So basically I'm making a generic class for rational numbers, and I want to do automatic type conversions in comparisons and operations and constructors. How would I go about doing this? Google has only returned results for template functions

rational.h

#ifndef RATIONAL_H
#define RATIONAL_H

class rational {
     
    public:
           rational();
           ~rational();
           template<typename type>
           rational(const type&);
     private:
           int n,d;
}

rational.cc

#include "rational.h"

rational::rational() {
n = d = 0;
}
rational::~rational(){
}

//heres where I don't know what to do
template<typename type>
rational::rational(const type&) {
//specialized function for int and float conversion
}

thanks for the help

Edited by SeeTheLite: made two public declarations

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by SeeTheLite
0

Something like this ? :

#include <iostream>
#include <vector>
#include <string>

using std::string;
using std::cout;
using std::endl;
using std::cin;

class RationalNumbers
{
private:
	float Numerator ;
	float Denominator ;
public :
	RationalNumbers() { }

	template<typename T>
	RationalNumbers(const T& RationalNumbers);
};
template<typename T>
RationalNumbers::RationalNumbers(const T& var){
	cout<<typeid(T).name()<<" specialized\n";
}
template<>
RationalNumbers::RationalNumbers(const int& var){
	cout<<"Int specialized\n";
}
template<>
RationalNumbers::RationalNumbers(const float& var){
	cout<<"Float specialized\n";
}
int main()
{ 
	 		
	float A = 4.2f;
	int B = 2;
	char C = 'a';
	string str;

	RationalNumbers R1(A);
	RationalNumbers R2(B);
	RationalNumbers R3(C);
	RationalNumbers R4(str);

	return 0;

}

denominator

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.