reference type as template argument

S

subramanian100in

consider
template<typename T> Test
{
// ...
};

We can have a pointer type as argument to a template class. For
example, we can have,
int x = 100;
Test<int*> obj(&x); // assuming a suitable ctor exists

But we cannot have reference type as template argument. This is
because reference cannot be assigned (in the overloaded assignment
operator) in the ordinary sense - that is, a reference cannot be
reseated. So, we cannot instantiate a template class with reference
type as argument. Is this understanding of mine, is correct ?

Kindly clarify.

Thanks
V.Subramanian
 
J

James Kanze

consider
template<typename T> Test
{
// ...
};
We can have a pointer type as argument to a template class. For
example, we can have,
int x = 100;
Test<int*> obj(&x); // assuming a suitable ctor exists
But we cannot have reference type as template argument.

Sure you can.
This is because reference cannot be assigned (in the
overloaded assignment operator) in the ordinary sense - that
is, a reference cannot be reseated. So, we cannot instantiate
a template class with reference type as argument. Is this
understanding of mine, is correct ?

No. Templates don't really pose any requirements on their
arguments, provided it corresponds: the argument to a type
parameter must be a type, the argument to an int parameter an
int, etc.

Actual templates typically will impose contraints, because they
do something with the type they are given. Thus, the containers
in the standard library require the type to be CopyConstructible
and Assignable, because they need to be able to copy construct
and assign objects of that type. You can't use references for
them, because references don't meet the requirements. You can't
use a class type which doesn't support copy construction or
assignment, either.

In practice, just about every real template will impose some
constraints. And it is fairly difficult to write a template
which will work equally well with both references and object
types. (There are some in Boost. But if you look at the code
for them, it's far from trivial.) But note that this is really
no different from functions: it's rather frequent to have
functions which take for example a double or an int, but
restrict the range. Templates are really no different in this
respect.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top