C2070 - illegal sizeof operand

前端 未结 2 810
忘了有多久
忘了有多久 2020-12-11 16:52

The following code looks fine to me:

    #include 

    template 
    struct A
    {
        static float m_kA[];
    };

           


        
相关标签:
2条回答
  • 2020-12-11 17:21

    http://ideone.com/3ssVi

    it compiles fine with G++.

    As far as i can see it can be related to this bug:

    http://connect.microsoft.com/VisualStudio/feedback/details/759407/can-not-get-size-of-static-array-defined-in-class-template

    0 讨论(0)
  • 2020-12-11 17:26

    It's well defined. Do note that in the class definition, m_kA is declared with type float[], which is an incomplete type and cannot be used in tandem with sizeof. In the definition of m_kA, it is redeclared to have type float[3], after which it is okay to use sizeof. (8.3.4 governs the meaning of array declarations.)

    From 3.4.6 Using-directives and namespace aliases [basic.lookup.udir]:

    10 After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.

    From 3.9.2 Compound types [basic.compound]:

    6 [...] The declared type of an array object might be an array of unknown size and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points (“array of unknown bound of T” and “array of N T”) are different types. [...]

    A workaround for your compiler issues would be to declare m_kA with a complete type outright. Another static member holding the size could be helpful, too.

    [ I'm quoting from C++11 but to the best of my knowledge C++03 followed the same rules. ]

    0 讨论(0)
提交回复
热议问题