Traits

The concept of traits exists already in C++. It is used in the standard library and was exposed in an article in C++ Report (June 95 - Vol 7/No 5, p 32: A new and useful template technique: "Traits", by Nathan Myers).

What I have in mind is an extension of this concept, which would need a specific support from the language: it would be a new category of templates.

These new templates would not introduce a new scope at instantiation, but use the one of the class used to parameterize them.

Let's put a syntax to make things more concrete, e.g. using a new "trait" keyword (maybe useful for parsing reasons - no claim that "trait" would be or not suitable as a new keyword, maybe "baggage" is better/more clash-free). The declaration:


template <class T> trait NoCopy {
  private:
    T(const T&);              // declared but not defined
    void operator=(const T&);
  public:
    T() {}                    // default restored
};
...could only be used by a class (here "trait" could be replaced with "template", or even removed altogether, in order to avoid introducing a new keyword):

class X: trait NoCopy {
    // whatever
};

There are many uses for such an extension. A first group would push further forward the need for macros (e.g. for streaming support in ObjectSpace of RogueWave toolkits). A more interesting group yet would exploit the better orthogonality of genericity vs inheritance, by allowing generic features to be specialized in derived classes.

Consider the problem in emulating this "trait" facility with current technology:


template <class T> class A {
  public:
    virtual void foo(T*);
};

class X: virtual public A<X> {};

If I want to specialized X into Y, there is no simple way in which I can override "foo" to be more specific when taking a Y as covariant input (er: there are ways, but they are complex and add indirections).

Note that the first example above cannot be fully satisfactorily replaced by a simple class NoCopy.


Table of contents
Marc Girod
Last modified: Sat Feb 28 14:29:39 EET 1998