2012-08-16 21 views
0

使用gcc編譯以下代碼時,出現錯誤:'i'不能出現在常量表達式中。爲什麼這個const參數不能匹配一個非類型的模板參數?

這是爲什麼?

#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; 
} 
+0

您不能將值賦給模板參數'p = 0'。 – 2012-08-16 04:18:45

回答

2

可變i是不能在運行時可變,因爲它是const,但它不是一個「常量表達式」,因爲它不是在編譯時進行評價。

(int)p;reinterpret_cast。積分常量表達式不能有reinterpret_cast。它是明確禁止的(§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);

— [...]

相關問題