tags:

views:

78

answers:

4

I can have

std::bitset< 10 > bitsetA;

or

const size_t LengthB = 20;
std::bitset< LengthB > bitsetB;

without any problem.

But, if the length is not const

size_t LengthC = 30;
std::bitset< LengthC > bitsetC;  // Line 30, say

I face the following compilation error

'LengthC' cannot appear in a constant-expression
template argument 1 is invalid

What is the reason for that?

What would be the problem, for compiler and for user code, if line 30 was to be accepted? Is it because LengthC might have some alias?

+3  A: 

Template arguments have to be declared const at compile time so that the template can be instantiated at compile time.

In the example you give, it does indeed appear that LengthC isn't going to change from the point where it is initialized to the point where the template has to be instantiated, so it could be treated as constant, but the compiler is not obligated to figure that out. The spec says the arguments have to be declared const, so that no compile-time flow control analysis needs to be done.

Kristopher Johnson
+7  A: 

Templates instantiate new types based off their template parameters, which is done at compile-time. You cannot instantiate new types at run-time, because C++ is statically-typed.

So when you have a non-const variable, it can't be passed as a template parameter because it can't be guaranteed to be that value (you'd have to potentially "instantiate a new type at run-time"). Only when it's const are you ensured the value is indeed constant, and therefore usable in a template parameter.

GMan
+1  A: 

Templates are compile-time creatures - variables are run-time ones. If you need to pass a variable to a template, you need to do it at run-time, for example in a templated class's constructor.

anon
+1  A: 

C++ compilers are strict when it comes to const casting.

Both 10 and const size_t LengthB = 20; evaluates to a constant. without the const keyword, the compiler cannot easily determine if the variable may change between declaration and usage.

Xavier Ho