flopbucket wrote:
Could someone explain to me what the difference is between function
template specialization and function overloading?
I guess overloading can change the number of parameters, but otherwise
they seem very similar to me - i.e. they both provide specialized
functions for depending on the parameter types.
They do different things in different ways. Overloading allows you to
call a different function depending on the arguments given:
void foo( int );
void foo( double );
void foo( int, int );
Are all fine, but you can't also have:
int foo( int );
Template specialisation allows you to define a function that works for
any type and specialising it allows you to specify a different
implementation for some of them. Here is a good example:
template<typename Tinline
std::wstring toString( const T & t ) {
std::wstringstream ss;
ss << t;
return ss.str();
}
This allows you to turn most types into a string automatically, but is
silly for strings so we do this:
template<inline
std::wstring toString< std::wstring >( const std::wstring &t ) {
return t;
}
What we cannot do though is this:
template<inline
std::wstring toString< double >( double v, int places ) {
//...
}
We can also have a difference in return type so we can do this:
template< typename T >
T variant_cast( const VARIANT &v );
And then specialise this for those types that need to pull data out of
the variant in odd ways.
Hope this helps.
K