Arman Arman - 8 days ago 4x
C++ Question

Default template arguments for function templates

Why are default template arguments only allowed on class templates? Why can't we define a default type in a member function template? For example:

struct mycclass {
template<class T=int>
void mymember(T* vec) {
// ...

Instead, C++ forces that default template arguments are only allowed on a class template.


It makes sense to give default template arguments. For example you could create a sort function:

template<typename Iterator, 
         typename Comp = std::less<
            typename std::iterator_traits<Iterator>::value_type> >
void sort(Iterator beg, Iterator end, Comp c = Comp()) {

C++0x introduces them to C++. See this defect report by Bjarne Stroustrup: Default Template Arguments for Function Templates and what he says

The prohibition of default template arguments for function templates is a misbegotten remnant of the time where freestanding functions were treated as second class citizens and required all template arguments to be deduced from the function arguments rather than specified.

The restriction seriously cramps programming style by unnecessarily making freestanding functions different from member functions, thus making it harder to write STL-style code.