I am leaning the topic templates in C++, it says I can also assign the datatype in the template syntax. But if I pass a different datatype in the object of class and call the method of my class it should throw an error or a garbage output, but it does not whereas it gives the correct output if I assign the datatype while declaring the object of the class and calling it. Why is so?
Here is the program I was practicing on
#include <iostream>
using namespace std;
template <class t1 = int, class t2 = int>
class Abhi
{
public:
t1 a;
t2 b;
Abhi(t1 x, t2 y)
{
a = x;
b = y;**your text**
}
void display()
{
cout << "the value of a is " << a << endl;
cout << "the value of b is " << b << endl;
}
};
int main()
{
Abhi A(5,'a');
A.display();
Abhi <float,int>N(5.3,8.88);
N.display();
return 0;
}
I am facing the issue in the first object A while the second object N gives the correct output
The output of the above program for the first object is
the value of a is 5
the value of b is a
The output of the above program for the second object is
the value of a is 5.3
the value of b is 8
>Solution :
A char can be implicitly converted to an int. Although the type of A will be deduced by C++20 to Abhi<int,char>. That’s why when you output it you get an a and not its corresponding integer representation.
See CTAD for a more detailed explanation of the mechanism.
More interesting is why your compiler implicitly converts double to int or float in N. This indicates that your compiler warning flags are insufficiently high or you are actively ignoring them.