sizeof in static const member initialization

前端 未结 4 1142
攒了一身酷
攒了一身酷 2021-01-23 14:00

I have such code:

class A
{
public:

    unsigned long a;
    static const unsigned long b = sizeof(a); // \"error C2327: \'A::a\' : is not a type name, static,          


        
4条回答
  •  感情败类
    2021-01-23 14:25

    StoryTeller's answer specifies why this didn't work on visual-studio-2005. Namely because it wasn't supported until c++11.

    As far as visual-studio-2013 it's not fully c++11 compliant. But I've validated that this code works around the deficiency:

    static const unsigned long b = sizeof(decltype(a))
    

    If you want something that will work with visual-studio-2005 as well, consider making b a global, instead of a static member of A:

    const unsigned long b = sizeof(A().a)
    

提交回复
热议问题