0

What is the difference between A, B and C calls?

#include <iostream>

using namespace std;

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

int main() {
    float a = 4.0;
    float b = 6.0f;
    cout << max(a, b) << endl; //A
    cout << max<double>(a, b) << endl; //B
    cout << max<double>(4.0, 6.0f) << endl; //C
}
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
Qorn
  • 189
  • 1
  • 1
  • 6
  • Same things, except return value and some implicit conversion (float -> double) – Fefux Nov 30 '16 at 11:57
  • This is how you find out what function is generated: To the function add this line: `std::cout << (__PRETTY_FUNCTION__) << std::endl;` – Adam Hunyadi Nov 30 '16 at 12:00

2 Answers2

2

First invocation of max is actually max<float>, second and third is the same max<double>

But in second invocation both a and b get promoted to double, where in third the example only 6.0f is promoted to double.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Starl1ght
  • 4,422
  • 1
  • 21
  • 49
-1

A calls std::max<float>, since a and b are float arguments. In B and C, you force it to call std::max<double>, thus both arguments are converted to double.

sp2danny
  • 7,488
  • 3
  • 31
  • 53