2017-01-14 16 views
0

以下のコードを参照してください。f()はmain関数の下で定義されていますが、不正なものとみなされますか? 誰も私にこのことについて説明できますか?constexpr関数を順方向に定義する必要がありますか?

constexpr int f(); 
void indirection(); 
int main() { 
    constexpr int n = f(); // ill-formed, `int f()` is not yet defined 
    indirection(); 
} 
constexpr int f() { 
    return 0; 
} 
void indirection() { 
    constexpr int n = f(); // ok 
} 

答えて

2

C++ 14標準は、(便宜上私短縮)次のコードスニペットを提供する:

constexpr void square(int &x); // OK: declaration 

struct pixel { 
    int x; 
    int y; 
    constexpr pixel(int); 
}; 

constexpr pixel::pixel(int a) 
    : x(a), y(x) 
{ square(x); } 

constexpr pixel small(2); // error: square not defined, so small(2) 
         // is not constant so constexpr not satisfied 

constexpr void square(int &x) { // OK: definition 
    x *= x; 
} 

溶液はsmallの宣言の上squareの定義を移動させることです。

上記から、constexpr関数を宣言しても問題ありませんが、その定義はより先にである必要があります。

2

constexpr何かは、それが使われている各ポイントで、コンパイル時に知られていなければなりません。

これは、不完全型の変数を宣言できない場合と同じです。たとえその型が後で同じソースに完全に定義されていても同じです。

関連する問題