Hi all. I am currently writing a large number class and was curious if I should use a template. I am setting up my constructors and I have one for a string and i was thinking i could use a template for a constructor so it can take in an int, float, double, etc. instead of writing a constructor for each type.

template<typename T>
Number
{
       Number();
       Number(string);
       Number(T);  // cover for built in number data types
}

I'm thinking this will make writing the code easier but I'm not sure if this will have unexpected consequences down the line. besides the fact some one could try and put a dog into the Number.

Yes, use template.

You could use template specialization, to make sure that the template
parameters is a number.

Here is a way to do that :

#include <iostream>

using namespace std;


template<typename Type>
struct is_numeric { static const int i = 0; };

//Template specilization
template<> struct is_numeric<short>				{ static const int i = 1; };
template<> struct is_numeric<unsigned short>	{ static const int i = 1; };
template<> struct is_numeric<int>				{ static const int i = 1; };
template<> struct is_numeric<unsigned int>		{ static const int i = 1; };
template<> struct is_numeric<long>				{ static const int i = 1; };
template<> struct is_numeric<unsigned long>		{ static const int i = 1; };
template<> struct is_numeric<float>				{ static const int i = 1; };
template<> struct is_numeric<double>			{ static const int i = 1; };
template<> struct is_numeric<long double>		{ static const int i = 1; };

template<typename Type>
class Numeric
{	
	//Check is Type is numeric
	int AssertType[is_numeric<Type>::i];

	Type * Vector_;
	unsigned int length;
public:
	Numeric()	{ Vector_ = new Type[0]; };
	~Numeric()  { delete [] Vector_; }
};

int main()
{ 
	Numeric<int> a;
	Numeric<float> b;
	Numeric<unsigned short> c;
	Numeric<string> d; //Error  
	Numeric<char> e; //Error  
	

	return 0;

}
commented: Nice, easy to understand template traits example +6

thanks much firstPerson.

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.