2

可能重复:
C2070 - 非法 sizeof 操作数

为什么下面代码的模板版本不编译,而当(未使用的)模板被删除时,相同的代码将编译?


不编译:

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
}

编译:

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

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

inline
int Foo::run () {
    return sizeof(vals);
}
4

1 回答 1

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);
}
于 2012-10-30T19:18:00.503 回答