Topic: const and template parameters


Author: vinoski@apollo.hp.com (Stephen Vinoski)
Date: Mon, 17 Aug 1992 21:57:58 GMT
Raw View
Recently I wondered about the use of const for the arguments of class
template member functions and function templates.  For example, given
this function template:

 template<class T>
 void
 tfunc(const T arg) { // ... }

what happens when the type ``int *'' is used for the formal template
parameter ``T''?

Mentally, one might make the parameter substitution and come up with
the following equivalent function:

 void tfunc(const int *arg);

Under this interpretation, the argument appears to be a pointer to
const int.

What actually should happen, though, is that const should apply to
``T'', so that the type parameter substitution results in

 void tfunc(int *const arg);

with the argument actually being a const pointer to int.

The latter interpretation is exactly the same as the "const applied to
typedef" problem:

 typedef int *IntPtr;
 const IntPtr int_ptr;

Here, int_ptr is a const pointer to int (sometimes much to the
amazement of C++ novices :-)).

It appears that the use of const under these circumstances is somewhat
misleading, and perhaps buys us very little.  Should developers leave
const out of these areas of function and class templates?  Your
thoughts?

thanks,
-steve

--
Steve Vinoski  (508)436-5904   vinoski@apollo.hp.com
Distributed Object Computing Program
Hewlett-Packard, Chelmsford, MA 01824       These are my opinions.




Author: checker@acf5.NYU.EDU (checker)
Date: 18 Aug 92 16:25:20 GMT
Raw View
vinoski@apollo.hp.com (Stephen Vinoski) writes:
> void tfunc(int *const arg);
>with the argument actually being a const pointer to int.
>The latter interpretation is exactly the same as the "const applied to
>typedef" problem:
> typedef int *IntPtr;
> const IntPtr int_ptr;
>Here, int_ptr is a const pointer to int (sometimes much to the
>amazement of C++ novices :-)).

The `solution' is to write your declarations like this:

simple-type-name type-specifiers

that means

int const foo;
instead of
const int foo;

The only disadvantage of doing it this way is that hardly anybody does.
I find it much clearer, especially when you get into complicated
declarations.

Chris