c++ - C2070 - 非法大小的操作数

标签 c++ visual-studio-2008 sizeof visual-c++

下面的代码对我来说没问题:

    #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\n", 
            sizeof(A<unsigned int>::m_kA) /
            sizeof(A<unsigned int>::m_kA[0]));
        return 0;
    }

但是当我用VC9编译时出现如下错误

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

我希望这段代码能够编译。我错过了什么吗?有谁知道解决这种奇怪行为的方法(请注意,没有模板的完全相同的事情可以正常编译并输出 3)。

请注意,删除模板不是一个选项,我制作这个示例是为了重现我在代码中遇到的问题,我需要包含数组的类型作为模板。

谢谢

最佳答案

定义明确。请注意,在类定义中,m_kA 声明为 float[] 类型,这是一个不完整的类型,不能与 sizeof 一起使用>。在 m_kA 的定义中,它被重新声明为 float[3] 类型,之后可以使用 sizeof。 (8.3.4 规定了数组声明的含义。)

从 3.4.6 使用指令和命名空间别名 [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.

来自 3.9.2 复合类型 [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. [...]

您的编译器问题的解决方法是完全声明具有完整类型的 m_kA。另一个持有大小的静态成员也可能有帮助。

[ 我引用的是 C++11,但据我所知,C++03 遵循相同的规则。 ]

关于c++ - C2070 - 非法大小的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12485025/

相关文章:

c - sizeof 运算符与可变长度数组一起作为函数参数

c++ - 如何将 sizeof() 运算符应用于非静态类成员方法?

c++ - 是否可以定义另一个预处理器指令?

visual-studio-2008 - 在Visual Studio 2008中重新使用内存

c++ - 使用静态库编译 C++

visual-studio-2008 - 维护多个 Visual Studio 用户选项 (suo) 配置文件

c# - 查看接口(interface)的方法时是否可以看到 "final"C# 代码?

c - 结构的大小 - c 中的 size_t

c++ - 如何将 wstring 缓冲区发送到子进程的标准输入?

c++ - 对于单精度矩阵运算,AVX 与 SSE 的 Eigen 性能没有差异?