Topic: Reference Types as Template Arguments


Author: jimad@microsoft.com (Jim Adcock)
Date: 27 Sep 93 21:20:40 GMT
Raw View
In article <1993Sep21.182355.16500@cs.brown.edu> sdm@cs.brown.edu (Scott Meyers) writes:
|All this leads me to wonder:  should reference types be legal as arguments
|to templates?
|

The basic design of templates is to be permissive on what a programmer
can attempt to expand a template on, the optimistic assumption being
that a nonsensical expansion attempt better result in a compiler-time
syntax error.  Given a permissive design for templates, your question
becomes: "could reference types ever make sense as arguments to templates?"
Clearly the answer is yes, it is easy to come up with templated functions
that do sensible things when expanded either on values or on references.

Consider something along the lines of:

template<class T> void PrintPair(T t1, T t2)
{
 cout << t1 << ' ' << t2 << '\n';
}

could be equally usable whether T is an object type, or a reference to
object type.





Author: sdm@cs.brown.edu (Scott Meyers)
Date: Tue, 21 Sep 1993 18:23:55 GMT
Raw View
I just discovered that templates can be instantiated with reference types.
Perhaps this should not have surprised me, but it did.  Consider this
code:

    template<class T>
    class StrangeCollection {
    public:
      void addByRef(const T&);
      void addByPtr(T*);
    };

    StrangeCollection<int&> x;

What are the signatures of the two member functions for
StrangeCollection<int&>?  It would seem that addByRef takes a const int&&,
which isn't a legal type; and it would seem that addByPtr takes a pointer
to a reference to an int, which is also not a legal type (and which is not,
I believe, the same as an int&*, which I imagine is the same as an int*&,
which is clearly legal).

For what it's worth, cfront seems to agree with me:

  error: bad initializer type: int  ( int && expected)
  error: bad argument  1 type for
         StrangeCollection<int &>::addByPtr(): int * ( int &* expected)

All this leads me to wonder:  should reference types be legal as arguments
to templates?

Scott