Const static member is a compile time variable, somtimes

So, I said in-class static initializer is compile time constant.

Except that it must be integral type.

What surprised me recently is this is not valid C++.

class Foo {
  // ERROR: double is not an integral type
  static const double v = 0.1;

Bjarne Stroustrup tries to explain it here but I don’t fully understand.

So why do these inconvenient restrictions exist? A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects. See D&E for an explanation of C++’s design tradeoffs.

I think I should read D&E again.


About Moto

Engineer who likes coding
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s