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_arbitrarily_long_name,
typename KIND = KIND_with_an_arbitrarily_long_name>
class Foo
{
public:
virtual void bar(TYPE& t, KIND& k) = 0;
};
And the part I don’t understand is the assignments inside the template:
template <typename TYPE = TYPE_with_an_arbitrarily_long_name, ..
I have been trying to understand the effect of this but so far I couldn’t produce any. Here are some stuff I have tried:
#include <iostream>
#include <typeinfo>
using namespace std;
template<typename T>
void foo(T t) {
cout << typeid(t).name() << " ";
}
template<typename T = int>
void bar(T t) {
cout << typeid(t).name() << " ";
}
template<typename T = double>
void baz(T t) {
cout << typeid(t).name() << " ";
}
int main()
{
cout << "\nfoo: ";
foo(3); foo<int>(3); foo<double>(3);
cout << "\nbar: ";
bar(3); bar<int>(3); bar<double>(3);
cout << "\nbaz: ";
baz(3); baz<int>(3); baz<double>(3);
return 0;
}
prints out:
foo: i i d
bar: i i d
baz: i i d
So my question is:
- What is the effect of assignment inside
template? - What is the purpose of using it in the above example?
- There is no third question.
Any help is appreciated..
EDIT turned out functions are only compilable with c++11
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::vectororstd::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.