2

In my code I'm adopting a design strategy which is similar to some standard library algorithms in that the exact behavior can be customized by a function object. The simplest example is std::sort, where a function object can control how the comparison is made between objects.

I notice that the Visual C++ provides two implementations of std::sort, which naturally involves code duplication. I would have imagined that it was instead possible to have only one implementation, and provide a default comparator (using operator< ) as a default template parameter.

What is the rational behind two separate versions? Would my suggestion make the interface more complex in some way? Or result in confusing error messages when the object does not provide operator< ? Or maybe it just doesn't work?

Thanks,

David

David Williams
  • 753
  • 1
  • 4
  • 11
  • 2
    "*I notice that the Visual C++ provides two implementations of std::sort, which naturally involves code duplication.*" Why would you think that? The obvious implementation is for the overload lacking a predicate argument to be implemented in terms of the overload taking a predicate argument (passing `std::less::value_type>()` for said argument). – ildjarn Jun 29 '12 at 15:19
  • _"Why would you think that?"_ - I'm looking at the implementation of algorithm which ships with Visual C++ and seeing two seperate implementations. – David Williams Jun 29 '12 at 15:26
  • That's a single, apparently poor implementation; I was picking on the word 'naturally', which is most certainly not accurate. – ildjarn Jun 29 '12 at 15:28

2 Answers2

12

Because function templates are not allowed by the standard to have default type arguments.

This, however, was amended in C++11, and now function templates can have default type arguments.

Community
  • 1
  • 1
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
2

Prior to C++11, a function template could not have default template arguments, and a template argument cannot be deduced from a default function argument, so there was no way to make this work.

In C++11, which supports default template arguments for function templates, you could use a single function template, but changing it now would break backwards compatibility with older C++ code that relies on the functions having a particular type.

James McNellis
  • 348,265
  • 75
  • 913
  • 977