views:

65

answers:

2

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!

+3  A: 

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.

Space_C0wb0y
Yeah, man I'm stupid sometimes :( Thank you.
John D.
A: 

Once you're at replacing C habits, check out streams:

int main()
{
    std::cout << min(1.3, 2.2) << '\n' 
              << add(1, 10) << '\n' 
              << add(5.1, 7.34) << '\n';
    return 0;
}
sbi
Missing semicolon ? And shouldn't it be `endl` rather than `'\n'` ?
Paul R
@Paul: Thanks for catching the semicolon, I fixed it. However, you rarely ever want to flush the stream manually, which is what `std::endl` does on top of outputting a `'\n'`. Therefor `std::endl` is almost always not needed, sometimes it's wrong. I have seen an app extensively writing data to the disk speedup by a factor of almost 10, when a few critical `std::endl` were replaced by `'\n'`. So my advice would be to only ever to use `std::endl` when you really want to flush the stream. (In the above example the stream will be flushed by application cleanup upon leaving `main()` anyway.)
sbi
@sbi: interesting point about `endl` versus `'\n'` - I hadn't considered that subtlety before - thanks for clarifying.
Paul R