🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

2 total messages Started by Valery Croizier Thu, 05 Oct 1995 18:05
Why no constraint templates ?
#2123
Author: Valery Croizier
Date: Thu, 05 Oct 1995 18:05
30 lines
1497 bytes
Sometimes, I wish I could oblige the user of a template class to
inherit from a given class:

class Shape {
public:
  void draw() = 0;
};

template <class T inherits from Shape>
class ListOfShape {
public:
// ...
  void drawAll();
};

Of course, the above is just an example, and we can find many other
use of such a kind of template.  The main advantage is compile-time
type-checking: when you write the implementation of the template class,
you cannot call a bad method.

  o Is there a way I have not noticed to do this ?
  o Does anybody know the reason why the team working on the
standard rejected this feature ?

--
Valery

[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Re: Why no constraint templates ?
#2129
Author: Steve Clamage
Date: Thu, 05 Oct 1995 18:43
33 lines
1830 bytes
In article 11m3@melimelo.enst-bretagne.fr, croizier@rennes.enst-bretagne.fr (Valery Croizier) writes:
>Sometimes, I wish I could oblige the user of a template class to
>inherit from a given class: ...
>
> ...
>  o Is there a way I have not noticed to do this ?
>  o Does anybody know the reason why the team working on the
>standard rejected this feature ?

This subject is discussed in D&E, including why C++ templates do not
have an explicit constraint mechanism.

Your particular case can be handled like this:

template< class T > // T must be derived from Shape
class C {
	C() { static_cast<Shape*>(static_cast<T*>(0)); ... }
};

The constructor won't compile unless there is an implicit conversion from
T* to Shape*, meaning that T* must be or be derived from Shape. The
result of the casts isn't used, so no code should be generated. 

If your compiler doesn't support static_cast, you can write
	Shape* p = (T*)0; // requires implicit conversion from T* to Shape*
---
Steve Clamage, stephen.clamage@eng.sun.com



[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads