Why only integral const statics inside a class?

So, I wrote this and read D&E but still could not understand why. (Tell me where in D&E I can find the discussion.) Some google search, however,  unveiled the issue recently.

http://groups.google.com/group/comp.std.c++/msg/0cbde331c9b8c28c?hl=en&

The cause seems to be a fact that C++ standard does not define the floating point arithmetic precisely and leaves it to each platforms. Let’s take an example.

class Foo {
public:
  const static float COMPILE_TIME_VAL = 0.1 * 10;
};

assert(Foo::COMPILE_TIME_VAL == 0.1 * 10);

Here, COMPILE_TIME_VAL is calculated by a compiler while the assert is evaluated by a platform processor. The compiler may use a floating point arithmetic method which is different from the platform where the program would be run. Therefore, the assertion can fail.

In general, the C++ standard avoids letting compiler do floating point calculation because it can result in different result from the one of target platform. For example, I happened to know that float is also not allowed in non-type template parameter while writing this post.

Non-type template parameters must be of integral, enumeration, pointer, reference, or pointer to member type, and must be constant at compile time. They can be qualified as const or volatile types. Floating point values are not allowed as template parameters.
http://msdn2.microsoft.com/en-us/library/x5w1yety.aspx

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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