Guys, I'm doing excercises from "The C++ Programming Language 3rd ed." and on page 340 there is an example of function:
template <class T, class C = Cmp<T> > // Here is a default argument
// But as far as I'm concerned it's illegal to have a default argument in
// a function template
int compare (const String<T>& str1, const String<T>& str2)
{
/*Some code*/
}
So my question is:
Is there a mistake in a book or I'm getting this wrong?
Templates are appropriate when defining an interface that works on multiple types of unrelated objects. Templates make perfect sense for container classes where its necessary generalize the objects in the container, yet retain type information.
What is Templates in C++? Templates in C++ is an interesting feature that is used for generic programming and templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Simply put, you can create a single function or single class to work with different data types using templates.
The reason templates are considered faster is that they are visible to the compiler.
Since template instantiation happens at compile time, there is no run-time cost to using templates (as a matter of fact templates are sometimes used to perform certain computations at compile-time to make the program run faster).
Yes, the book is wrong in this case. It is indeed illegal to use default template arguments in function template declarations.
You can find the reference to that issue here http://www2.research.att.com/~bs/3rd_issues.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With