tags:

views:

87

answers:

3

HI, I started learning C++ STL's i am just trying some small programs.one of them is below:

inline int const& max (int const& a, int const& b) 
{
    return  a < b ? b : a;
}

template <typename T>
inline T const& max (T const& a, T const& b)
{
    return  a < b ? b : a;
}

int main()
{
    ::max(7, 42);         // calls the nontemplate for two ints
    ::max<>(7, 42);       // calls max<int> (by argument deduction)
    ::max('a', 42.7);     // calls the nontemplate for two ints
}

I have some basic questions!!

  1. why is the scope resolution operator used here?

  2. why/how is that calling ::max<>(7, 42) will assume that the parameter passed are

    integers?

+3  A: 
  1. Presumably to avoid conflicts with std::max

  2. It's not assuming that the parameters are integers, it sees that the parameters are integers. It then assumes that the template argument is int because the parameters are integers.

sepp2k
#1 doesn't matter unless he has `using namespace std;` or `using std::max;` somewhere, btw.
Roger Pate
+6  A: 

1) why is the scope resolution operator used here?

Probably to differentiate the max declared here from the one in (for example) the std:: namespace.

2) why/how is that calling ::max<>(7, 42) will assume that the parameter passed are integers?

It doesn't have to assume anything - integer literals have the type int.

And to answer the question you didn't ask:

 max('a', 42.7);

matches the non-template version because type conversions are not performed on templated parameters, but are performed on non-template ones.

anon
A: 

For 2) what you possible mean is that why does it work - the template does not require integers, just any types on which the "<" operator is defined. An integer fulfills this so it is ok to pass it to the template method.

ron