Re: Template - class/typename difference
JCR ha scritto:
Hello.
The following code does compile:
template<template<typename T> class C, typename T>
C<T> foo(C<T> a, C<T> b)
{
return C<T>();
}
but I am curious about two issues:
1. If I write "typename C" instead of "class C", the code does not
compile any more. How comes? I thought that typename and class were
equivalent in a template declaration
There are three types of template arguments:
1) type (the usual case) as in "template <typename T>" or "template
<class T>"
2) non-type as in "template <int N>"
3) template as in "template <template <WHATEVER> class C>"
typename and class are equivalent keyword only when describing arguments
of type 1, as shown. Notice that WHATEVER in case 3 is recursively a
list of template arguments so the argument applies also to WHATEVER, but
in the "class C" that follows the typename keyword is NOT allowed.
2. It appears that "template<template<typename T> class C>" does not
compile and that the ", typename T> is necessary. Why should I specify
T again, especially outside of the template template parameter?
The first typename T only describe a formal parameter of the first
template argument C. The name of formal parameter is completely ignored
and it's not introduced in the rest of the construct. The following
syntaxes are BOTH equivalent to yours:
template<template<typename FORMAL_PARAMETER> class C, typename T>
C<T> foo(C<T> a, C<T> b)
{
return C<T>();
}
template<template<typename> class C, typename T>
C<T> foo(C<T> a, C<T> b)
{
return C<T>();
}
If you think it this way, it's clear why you still need to introduce T
in some way in order to use it in the rest of the definition.
HTH,
Ganesh
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]