Reputation: 421
When compiling the code below with gcc, I get an error: 'i' cannot appear in a constant-expression.
Why is this?
#include <iostream>
using namespace std;
template<int p>
class C
{
public:
void test();
};
template<int p>
void C<p>::test()
{
p = 0;
}
char const *const p = "hello";
int main()
{
const int i = (int)p;
C<i> c;
}
Upvotes: 0
Views: 111
Reputation: 234474
The variable i
is not mutable at runtime because it is const
, but it is not a "constant expression" because it is not evaluated at compile-time.
(int)p;
is a reinterpret_cast
. Integral constant expressions cannot have reinterpret_cast
. It is explicitly forbidden (§5.19/2):
A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression (§3.2), but subexpressions of logical AND (§5.14), logical OR (§5.15), and conditional (§5.16) operations that are not evaluated are not considered [Note: An overloaded operator invokes a function.—end note ]:
— [...]
— a
reinterpret_cast
(§5.2.10);— [...]
Upvotes: 2