2

Possible Duplicate:
C2070 - illegal sizeof operand

Why doesn't the templated version of the code below compile, whereas the same exact code will compile when the (unused) template is removed?


Does not compile:

template <typename T>
class Foo {
public:
    static double const vals[];
    int run ();
};

template <typename T>
double const Foo<T>::vals[] = { 1, 2,3 };

template <typename T>
inline
int Foo<T>::run () {
    return sizeof(vals); // error C2070: 'const double []': illegal sizeof operand
}

Compiles:

class Foo {
public:
    static double const vals[];
    int run ();
};

double const Foo::vals[] = { 1, 2,3 };

inline
int Foo::run () {
    return sizeof(vals);
}
Community
  • 1
  • 1
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106

1 Answers1

0

Because Visual Studio is broken. See: http://connect.microsoft.com/VisualStudio/feedback/details/759407/can-not-get-size-of-static-array-defined-in-class-template

A possible (untested) workaround would be to use something like this:

private:
template<typename T, int size>
int get_array_length(T(&)[size]){return size;}

And then use:

int Foo::run() {
    return get_array_length(vals) * sizeof(double);
}
Edward Loper
  • 15,374
  • 7
  • 43
  • 52