Program to convert decimal to binary using templates
Templates in C++ allow you to write generic and reusable code. By using function templates, you can create flexible functions that work with various data types. In this tutorial, you’ll learn how to write a C++ program to convert a decimal number to binary using a function template, enhancing both your understanding of binary number systems and generic programming.
#include<iostream.h>
#include<math.h>
template<class T>
class convert
{
private:
int base, rem, t1;
long y;
public:
void asctobin(T p)
{
y=base=0;
t1=p;
while(t1>0)
{
rem = t1%2;
y = y+rem*pow(10,base);
base++;
t1=t1/2;
}
}
void display()
{
cout<<"Binary value is: "<<y<<endl;
}
};
void main()
{
convert c;
int num;
cout<<"Enter the decimal number: "; cin>>num;
a.asctobin(num);
c.display();
cout<<endl;
}
OUTPUT Enter the decimal number: 124 Binary value is: 1111100
Advantages of Using Templates:
- Reusability: Same function can work with different data types.
- Flexibility: Helps build more generic and type-safe code.
- Efficiency: Reduces code duplication, especially useful in large-scale applications.
Conclusion:
Using function templates in C++ for converting decimal to binary not only improves code reusability but also introduces a powerful feature of C++ — generic programming. This example makes binary conversion flexible for any numeric type with minimal code change.


