mark mark - 18 days ago 6
C++ Question

In C++ how can we define a static const within a class that computes size of class member variables?

Does not compile:

class A
{
int m_x;
public:
static const int SIZE = sizeof(m_x);
};


I want to have
A::SIZE
. How can we do it?

I am using Visual Studio 2015. Here is the error:

1>c:\users\markk\documents\visual studio 2015\projects\b\b.cpp(10): error C2327: 'A::m_x': is not a type name, static, or enumerator
1>c:\users\markk\documents\visual studio 2015\projects\b\b.cpp(10): error C2065: 'm_x': undeclared identifier


Compilation command line:

/Yu"stdafx.h" /GS /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"x64\Debug\vc140.pdb" /Zc:inline /fp:precise /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /MDd /Fa"x64\Debug\" /EHsc /nologo /Fo"x64\Debug\" /Fp"x64\Debug\b.pch"


EDIT 1

Thanks to Stargateur. With a slight change it works on VS2015 too:

class A
{
int m_x;
public:
static const int SIZE;
};

const int A::SIZE = sizeof(A::m_x);


Turned out easier than I thought.

Answer

Just read doc

foo.h

#include <cstddef>

class Foo
{
private:
    int bar;
public:
    static size_t const foo;
};

foo.cpp

#include "foo.h"

size_t const Foo::foo = sizeof(Foo::bar);