c++ templates

K

krchandu

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?
 
Z

Zeppe

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
 
A

aman.c++

Here said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top