Default Argument or Overloading?

While testing the XSD-generated code on IBM XL C++ 7.0, I discovered an interesting difference between expressing the same semantic using default arguments and function overloading. Consider the following code snippet:

template <typename X>
struct sequence
{
  void resize (size_t, X const& x = X ());
};

What happens when the template argument for X does not have a default constructor? The majority of C++ compilers think this is fine as long as you don’t call resize with the default values for its second argument. But IBM XL C++ 7.0 does not. While I agree that we only need the default constructor at the function’s call site, it is still a part of the interface. If we were to write something like this:

template <typename X>
struct sequence
{
  void f (typename X::foo);
};

And the template argument for X didn’t have a type named foo, then it would have been an error even though we might never actually have called f. Fortunately, it is fairly easy to resolve this issue by rewriting the original example using overloading instead of the default argument:

template <typename X>
struct sequence
{
  void resize (size_t);
  void resize (size_t, X const&);
};

Comments are closed.