Home > Back-end >  Why aren't the default arguments of my template used in this case
Why aren't the default arguments of my template used in this case

Time:10-27

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

CodePudding user response:

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.

CodePudding user response:

When you write Abhi A(5,'a');, it doesn't use the default arguments of the Abhi template, instead the template type arguments are deduced from the constructor arguments values, in this case A is an Abhi<int, char>. This is a process called Class Template Argument Deduction.

You would get the default arguments if you wrote Abhi<> A(5, 'a');.

When you write Abhi <float,int>N(5.3,8.88); you have specified the types, but C allows conversion between arithmetic types. Unfortunately that includes discarding the fractional part when converting a decimal to int. Often there are settings for your compiler to warn of or forbid these lossy conversions.

The conversion from char to int isn't problematic, because there is an int value for every char value.

We can see that all here

  • Related