Document number: n2141=06-0211

Alisdair Meredith
2006-11-06

Strong Typedefs in C++09(Revisited)

Background

There has long been a concern that in a staticly typed language such as C++ where much functionality is driven by the type system, such as function overload resolution and template type deduction, there is a need to create type aliases that are distint from the original type but with identical semantics. The typedef keyword is insufficient, in that it only creates an alias for a type rather than a distinct new type.

Several papers have already been brought to evolution to consider the subject, and were given a favourable review. c.f. n1706 and n1891.

Current Progress for C++09

One new feature currently under review for C++09 is the idea of implicitly generating forwarding constructors to a base class (n2119.) Using this new feature it becomes possible to create something very like the required strong typedef. For example:


struct MyType : std::string {
  using string::string;
};

This type is distrinct from std::string, functions can be overloaded on this type as well as std::string, yet std::string is not convertible to this type.
Note: This may make initializing MyType interesting, although user may wish to declare an explicit constructor taking a single std::string argument for convenience.

Issues still to be addressed

While forwarding constructors go a long way to address the basic need, there are several issues with the functionality it offers when considered strictly as the syntax for a strong typedef.

The derived type will always be implicitly convertible to the base type. In the case of the example, this means that while std::string cannot be passed to functions requiring a MyType object, the converse is not true.

There is no support for strong typedefs of fundamental types, which is also a common motivation for the feature. In particular, there is no way to declare a strong int or enum typedef.

There is no support for types with private constructors (other than the copy or default constructors.) Such classes would be ill-formed under proposal n2119.

Conclusion

A new syntax is still required to address these additional needs. In particular, the nature of convertabilty between types should be explictly addressed.