Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why is my code accepting other data types along with the given datatype in template?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading