C2070 - illegal operand size

The following code looks good 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\n", 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 same thing without a template compiles fine and produces 3).

Note that deleting the template is not an option; I made this example to reproduce the problem that occurs in my code where I need a type containing an array, which should be a template.

thanks

+7
source share
2 answers
+5
source

He is well defined. Note that in the class definition, m_kA declared with the type float[] , which is incomplete and cannot be used in tandem with sizeof . In the definition of m_kA it is updated with the type float[3] , after which sizeof can be used. (8.3.4 determines the value of the array declarations.)

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

10 After all type settings (during which typedefs (7.1.3) are replaced by their definitions), the types indicated by all declarations related to this variable or function should be the same, except that declarations for an array object can indicate array types , which differ by the presence or absence of the main array binding (8.3.4). Violation of this rule for type identity does not require diagnostics.

From 3.9.2 Connection Types [basic.compound]:

6 [...] The declared type of an array object may be an array of unknown size and, therefore, be incomplete at one point of the translation unit and end later; array types at these two points ("array of unknown boundary T" and "NT array") are different types. [...]

A workaround for your compiler problems would be to declare m_kA with a full type. Another static member supporting size can also be useful.

[I quote C ++ 11, but as far as I know, C ++ 03 adhered to the same rules. ]

+4
source

All Articles