Search code examples
c++templatesmalformed

Simple simple template returning odd numbers?


EDIT BEFORE YOU READ: Sorry.. I didn't add newline so it appeared jumbled, I can't delete the question because I'm not registered yet, sorry for wasting your time guys.

I just used a template for the first time (for finding MIN of two numbers) instead of a macro, and I liked it! But when I tried to modify and make my own template it failed completely.. Here is my code:

#include <stdio.h>

template <class T> T min(T a, T b) { 
    return a < b ? a : b; 
};

//My attempt now.. because add could be int, float, etc; I wanted a template.
template <class T> T add(T a, T b) {
    return a + b;
};

int main(){

    printf("%f\n", min(1.3, 2.2));  //(Does not appear in console?)
    printf("%d", add(1, 10));       //1.300000 (how is an int show as float? lol)
    printf("%f", add(5.1, 7.34));   //1112.440000
    return 0;
}

Now the strange results are in the comments.. Min works fine, but when I change it from comparison to "a + b" it stops min from working, and hands me weird float values?!

Am I using it the wrong way? , is it supposed to be something else? what does that mean? I understand the basics so a simple explaination would be alright.Thank you!


Solution

  • Try adding linebreaks after the other lines too.

    What happens is this:

    1. it prints min(1.3, 2.2) which is 1.300000
    2. it prints a linebreak
    3. it prints add(1, 10), which is 11
    4. it prints add(5.1, 7.34) which is 12.440000

    Since there is no linebreak between step 3 and 4, it prints the number directly after each other, making it look like this: 1112.440000.