0

intgral 型の非型テンプレート引数は const 式でなければならないことはわかっています。

template <int E>
class cat
{
public:
    int array[E];
};

int main()
{
    cat<4> ob; // ??
}

私が読んだことから、式でconst初期化される変数のみconstconst式です。この例では がint E = 4;あるので、式Eにはなりませんconst

では、なぜcat<4> ob;エラーが発生しないのでしょうか? ここで何か不足していますか?コンパイル時に不明な場合
、どのようint array[E];に作成されますか?E

4

2 に答える 2

3

Whatever you read was rather incomplete.

Constant expressions also include literals (like 4), enumerators, sizeof expressions, the results of constexpr functions with constant arguments (since 2011), as well as const variables. Any of these with integer type can be used as an integer template argument.

There are probably a few others that I haven't thought of, and any complex expression built from constant expressions is also a constant expression.

于 2012-07-03T13:59:50.913 に答える
2

E4実際のコンパイルが始まる前です。テンプレートの特殊化はその前に行われます。つまり、コンパイラによって実際に見られるコードは次のようなものです。

 class cat4
 {
 public:
 int array[4];
 };

 int main()
 {
 cat4 ob;
 }

これはかなり大雑把な解釈です。勝手に解釈しないでください。

このシナリオを実際にテストするには、次を試すことができます。

 template <int E>
 class cat
 {
 public:
 int array[E];
 };

 int main()
 {
 int k = 4;
 cat<k > ob; // ??
 }
于 2012-07-03T13:50:06.563 に答える