template function v.s. template class

This is a discussion on template function v.s. template class within the C++ Programming forums, part of the General Programming Boards category; Hello everyone,
I am feeling template function is more tricky than template class. For the reason that the compiler will ...

template function v.s. template class

Hello everyone,

I am feeling template function is more tricky than template class. For the reason that the compiler will do the matching automatically for template function, but for template class, developer can assign how to match.

Sometimes compiler is doing mysterious matching rules for template function, which makes us confused. Does anyone have the same senses? :-)

Example,

1. for template function

we define

Code:

template <class T> void sort (vector <T>&)

when we invoke like,

sort (vector<int>)&, T will automatically matched by compiler to int -- we have no control. Sometimes, how compiler will do the matching is mysterious. :-)

2. for template class

developer has full control. For example, when use some template class, developer can assign the type of parameter,

we define,

Code:

template <class T> class Foo
{
// ...
}

when developer use it, we can explicitly assign the type, like Foo <int> or Foo <bool>.

They are the same, only a class requires you to pass a type for the template, functions do not. But you can specify the templates for both. Sometimes, the compiler can get confused and ask you to specifically tell it what types you are passing to a function.