Incomplete type is not allowed in a class, but is allowed in a class template

前端 未结 4 1230
野的像风
野的像风 2021-02-07 03:50

The following is invalid code:

struct foo {
    struct bar;
    bar x;        // error: field x has incomplete type
    struct bar{ int value{42}; };
};

int mai         


        
4条回答
  •  旧时难觅i
    2021-02-07 04:13

    I'll answer the third part of your question - as IANALL (not a language lawyer).

    The code is invalid for the same reason it's invalid to use a function before it has been declared - even though the compiler can figure out what the function's supposed to be by going further down in the same translation unit. And the cases are similar also in the sense that if you happen to have just a declaration with no definition, that's good enough for the compiler, while here you happen to have a template definition before the instantiation.

    So the point is: The language standard mandates that the compiler does not look ahead for you when you want to define something (and a class template is not a definition of a class).

提交回复
热议问题