0

I know that non-type template argument for intgral type must be const expression so:

template <int E> class cat { public: int array[E]; }; int main() { cat<4> ob; // ?? } 

From what I've read only const variables that get initialized with const expressions are const expressions. In this example, we have int E = 4;, so E will not be a constexpression.

So why doesn't cat<4> ob; throw an error? Am I missing something here?
And how will int array[E]; be created if E is not known at compile time?

2
  • 7
    4 is a compile time constant. Commented Jul 3, 2012 at 13:48
  • @hmjd Im talking about E. when I did cat<4> ob; it like telling the compiler to create the variable E and set it to 4, and since E is non-const int. so the value of E will not be known at compile time. so array[E] will throw an error. Commented Jul 3, 2012 at 13:53

2 Answers 2

3

Whatever you read was rather incomplete.

Constant expressions also include literals (like 4), enumerators, sizeof expressions, the results of constexpr functions with constant arguments (since 2011), as well as const variables. Any of these with integer type can be used as an integer template argument.

There are probably a few others that I haven't thought of, and any complex expression built from constant expressions is also a constant expression.

Sign up to request clarification or add additional context in comments.

Comments

2

E is 4 before actual compilation starts. Template specialization takes place before that, which means that the code actually seen by the compiler is something like

 class cat4 { public: int array[4]; }; int main() { cat4 ob; } 

This is a fairly loose interpretation, don't take it ad-litteram.

To really test this scenario out, you can try:

 template <int E> class cat { public: int array[E]; }; int main() { int k = 4; cat<k > ob; // ?? } 

5 Comments

Im talking about E. when I did cat<4> ob; it like telling the compiler to create the variable E and set it to 4, and since E is non-const int. so the value of E will not be known at compile time
@AlexDan you're thinking about templates the wrong way. E is not a variable, it's a template parameter. IMO templates are closer to macros than they are to actual classes.
@AlexDan It's not accurate to call E a variable and in fact for all practical matters it doesn't vary.
@LuchianGrigore : so E will be replaced by the value 4. if it's true, than this explain everything to me.
@AlexDan yes, and by whatever other values you specialize the template on. You can also have cat<5> and cat<1> and they all generate different classes with different sizes for the inner array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.