Re: template with const as parameter
On Jun 9, 8:17 am, MiB <michael.boehni...@gmail.com> wrote:
On Jun 9, 7:42 am, charlie <charlie.xia....@gmail.com> wrote:
const float t = 0;
template < class T, const T& >
class A {
public:
A();};
typedef A<float, t> AA;
why above doesn't work and gives following errors?
The second template parameter is the culprit.
1. Only types and values of integral types are allowed as template
parameters - float is not an integral type,
This is false. A non-type template parameter may be 1) an
integral or enumeration type, 2) a pointer to an object or
a function, 3) a reference to an object or a function, or 4)
a pointer to member. His parameter corresponds to 3.
so you cannot use it for a value template parameter.
2. Also, you cannot use references as specifiers of value template
arguments: the reference is in a way a hidden
pointer and receives a value at runtime. Template instantiation is
performed at compile time. Thus, while the
value of t is known by the compiler, its address in memory is not
yet determined and the template mechanism
must fail.
=A714.1/4 says otherwise, and explicitly lists references as legal
parameters.
3. You did not give a name to the second parameter, only its type. How
do you plan to reference the value from
the instantiation in your class definition?
That shouldn't stop the code from compiling.
The error messages you get are admittedly not very enlightening.
No. It does look like the compiler got confused.
In fact, the problem with his code is a frequent one: the
arguments to a template must have external linkage, and const
variables at namespace scope have internal linkage by default.
Just change the first line to:
extern float const t = 0;
and his code works. The problem has nothing to do with
float---I've had similar problems (with a similar fix) for
char const*.
--
James Kanze