Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

c++ - C2070 - illegal sizeof operand

The following code looks fine to me:

    #include <stdio.h>

    template <typename T>
    struct A
    {
        static float m_kA[];
    };

    template <typename T>
    float A<T>::m_kA[] = {1.0f, 2.0f, 3.0f};

    int main()
    {
        printf("%d
", 
            sizeof(A<unsigned int>::m_kA) /
            sizeof(A<unsigned int>::m_kA[0]));
        return 0;
    }

But when i compile with VC9 i get the following error

error C2070: 'float []': illegal sizeof operand

I would expect this code to compile. Am i missing something? Does anyone know a way to fix this strange behavior (note that the exact same thing without the template compiles fine and outputs 3).

Note that removing the template is not an option, i made this example to reproduce a problem that i'm having in a code where i need the type containing the array to be a template.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...