[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

c++ templates

krchandu

9/10/2008 6:40:00 AM

inline int const& max (int const& a, int const& b)
{
cout << "Normal function called \n";
return a<b?b:a;
}

// maximum of two values of any type
template <typename T>
inline T const& max (T const& a, T const& b)
{
cout << "Template function with 2 param called \n";
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)
}


Here, function call max<>(7, 42); instantiate the max template for int
as if it was declared and implemented individually. But there is a non-
template function with same signature. How can it be possible to have
two functions with same signatures?

2 Answers

Zeppe

9/10/2008 8:30:00 AM

0

krchandu@gmail.com wrote:
> inline int const& max (int const& a, int const& b)
> {
> cout << "Normal function called \n";
> return a<b?b:a;
> }
>
> // maximum of two values of any type
> template <typename T>
> inline T const& max (T const& a, T const& b)
> {
> cout << "Template function with 2 param called \n";
> 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)
> }
>
>
> Here, function call max<>(7, 42); instantiate the max template for int
> as if it was declared and implemented individually. But there is a non-
> template function with same signature. How can it be possible to have
> two functions with same signatures?

Template specialisation: after the template function declaration, you
declare a specialisation for int:

template<>
inline int const& max(int const& a, int const& b)
{
cout << "specialised function called \n";
return a<b?b:a;
}

In this case, the second function call will use the specialised function.

Best wishes,

Zeppe


aman.c++

9/10/2008 9:53:00 AM

0

> Here, function call max<>(7, 42); instantiate the max template for int
> as if it was declared and implemented individually. But there is a non-
> template function with same signature.  How can it be possible to have
> two functions with same signatures?

Internally these 2 functions get mangled to different names. Other
things being equal, the non-template function is preferred in
selecting what gets called. To force the template version to get
called you need to write ::max<int>(7, 42) or ::max<>(7,42)

regards,
Aman Angrish