C 尺寸不适合模板

C++ sizeof does not work with template

本文关键字:不适合      更新时间:2023-10-16

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

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


不编译:

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);
}

因为视觉工作室被打破。请参阅:http://connect.microsoft.com/visualstudio/feedback/details/759407/can-not-get-size-size-of-size-of-static-aray-aray-aray-defined-in-class-class-template

可能的(未经测试的)解决方法是使用类似的东西:

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

然后使用:

int Foo::run() {
    return get_array_length(vals) * sizeof(double);
}