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

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

yeah, thats pretty similar to what I'm looking for; many thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.