Elements of constant array as template arguments.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrzej 'Foxy' D.

    #1

    Elements of constant array as template arguments.

    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 :))

    --
    Pozdrawiam, Andrzej
  • Victor Bazarov

    #2
    Re: Elements of constant array as template arguments.

    Andrzej 'Foxy' D. wrote:[color=blue]
    > 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.[/color]

    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'.
    [color=blue]
    > 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.[/color]

    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
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask


    Comment

    Working...