Elements of constant array as template arguments.

V

Victor Bazarov

Andrzej said:
I cannot figure out, why is the following code incorrect:

const int array[] = { 1 };
const int var = 1;

template<int I>
struct Blah {};

int main() {
Blah<var> b1;
Blah<array[0]> b2; // ERROR!
}

I know that template arguments can only be constant expressions. But
I don't understand why isn't 'array[0]' treated as a constant
expression.

Indexing is a run-time thing. 'array' is converted to a pointer and
then indexing is performed on that pointer. It does not qualify as
a compile-time constant expression which is defined in subclause 5.19.
Pointers just cannot be part of a constant expression except as
arguments of 'sizeof'.
It seems to me that if an array is const and the index is
a constant expression (e.g. 0), then the whole expression is
constant. I can't imagine, how a compiler can NOT know, what's the
value of array[0] during compile-time.

The langauge just doesn't specify it that way. As to why it is so,
ask in 'comp.std.c++', they could explain the rationale behind
different parts of the Standard.

V
 
A

Andrzej 'Foxy' D.

Hi!

I cannot figure out, why is the following code incorrect:

const int array[] = { 1 };
const int var = 1;

template<int I>
struct Blah {};

int main() {
Blah<var> b1;
Blah<array[0]> b2; // ERROR!
}

I know that template arguments can only be constant expressions. But I don't
understand why isn't 'array[0]' treated as a constant expression. It seems
to me that if an array is const and the index is a constant expression
(e.g. 0), then the whole expression is constant. I can't imagine, how a
compiler can NOT know, what's the value of array[0] during compile-time.

I would be grateful, if you explained me this issue.

Thanks in advance! (I hope, you understand me :))
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top