Re: template with const as parameter
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,
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.
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?
The error messages you get are admittedly not very enlightening.
Summing it up:
template <class T, float t> class A {}; // illegal for reason #1
template <class T, int& i> class B {}; // illegal for reason #2
template <class T, int> class C {}; // illegal for reason #3
template <class T, T t> class D {};
D<float, 42.0f> d; // illegal for reason #1
delayed to instantiation.
D<int, 42> e; // this one should be OK.
best,
MiB.