I have come across this piece of code (I\'m trying to include all details in case I\'m missing something):
template< typename TYPE = TYPE_with_an_arbitrar
Foo<>
is the same as Foo<TYPE_with_an_arbitrarily_long_name, KIND_with_an_arbitrarily_long_name>
, and Foo<int>
is the same as Foo<int, KIND_with_an_arbitrarily_long_name>
.Foo
at all, and the parameters of baz
and bar
will always be deduced by the compiler from the given arguments.A function-template may not be the best construct to demonstrate default template arguments. Here's something similar with template-structs:
#include <iostream>
#include <typeinfo>
template<typename T = int>
struct foo {
static void f() {
std::cout << typeid(T).name() << "\t";
}
};
template<typename T = double>
struct bar {
static void f() {
std::cout << typeid(T).name() << "\t";
}
};
int main() {
foo<>::f(); foo<int>::f(); foo<double>::f(); std::cout << std::endl;
bar<>::f(); bar<int>::f(); bar<double>::f(); std::cout << std::endl;
}
Running this, I get:
% ./a.out
i i d
d i d
These are default template arguments. You can use template default arguments to simplify their usage.
When you have two template parameters, for example, and give the last one a default type, you must specify only one type.
std::vector, for example, is defined as
template < class T, class Allocator = allocator<T> > class vector;
Here you have a default template argument for Allocator
, so you can define vectors with just one argument
std::vector<int> v;
What you are looking for is "Template Specialization"
Here's a link to some Example/Explanation
These are not assignments but rather “default values” for the type arguments of the template, much like there is a similar syntax for default value arguments of functions. They are used when an explicit argument is not specified.
For bar
and baz
function templates in your example, it makes no sense because for these functions, T
will be derived from the specified arguments.
This is called 'default template argument' and specifies which type is used, when none is specified - alike default function parameters. This technique is widely used for classes - look at definition of std::vector or std::string, and you will see they have multiple default type parameters.
Best use for default type parameters for function templates is when type argument cannot be easily deduced from actual arguments, and it is not specified explicitly - then compiler will use default one. In your example there is no need for default types, because it can be easily deduced from actual call parameters.
Until C++0x default type parameters were allowed only for class templates - they were not possible to use with function templates. With C++0x it changed, but some older compilers (for example Visual C++ 2008) would not let you to use them.