The following program compiles:
template <const int * P>
class Test{};
extern const int var = 42; //extern needed to force external linkage
int main()
{
Test<&var> test;
}
This one, however, doesn't, which is a surprise for me:
template <const int * P>
class Test{};
extern const int var = 42; //extern needed to force external linkage
extern const int * const ptr = &var; //extern needed to force external linkage
int main()
{
Test<ptr> test; //FAIL! Expected constant expression.
}
Alternative example:
int main()
{
const int size = 42;
int ok[*&size]; //OK
const int * const pSize = &size;
int fail[*pSize]; //FAIL
}
I have concluded that a pointer just can't be a constant expression regardless of whether it's const and initialized with a constant expression.
Questions:
- Is my conclusion true?
- If so, why can't a pointer be a constant expression? If not, why don't the above programs compile?
- Does C++0x(C++11, if you will) change anything?
Thanks for any insights!