* Miguel Guedes:
Well, yes. But I'm interested in knowing the reason why they chose to
differentiate the way non-integrals are initialized. Anyone knows?
No. It has been discussed before, several times. And the upshot seems
to be that if other types than integral types were to be allowed, then
it was feared that this would open up a hornet's nest of issues the
commitee would then have to deal with. I'm not sure what those issues
would be; constants of class types have been mentioned, but I think
that's a red herring class misunderstanding.
But note that the current standard only allows use of such constants as
pure compile time values (i.e. not taking address), unless you define
the constant outside the class, i.e. in a separately compiled file, e.g. as
int foo::i;
which looks suspiciously like a pure declaration, but is actually a
definition, and what looks like a definition in the class definition, is
actually a pure declaration. Formally. And different compilers differ
in how strictly they interpret the standard, or how they interpret it.
In other words, the whole thing is a kludge, probably tacked on to the
language because of pressure from some sub-group of the committee, and
what was accepted was probably the minimum needed to make 'em shut up.
Now, as device for introducing a named, typed non-integral constant in
the class definition /in a header file/, without any separately compiled
definition, you can alternatively use the templated constant trick,
which as far as I know has only been put forward by me, and not even I
use it -- it's strictly a "yes there is a (painful) way" thing:
#include <iostream>
#include <ostream>
template< typename Dummy > struct FConstant { static float const f; };
template< typename Dummy > float const FConstant<Dummy>::f = 0.02f;
class Foo
: public FConstant<void>
{
// Whatever, here we have foo::f.
};
int main()
{
std::cout << Foo::f << std::endl;
}
Checking that this compiles & works... Yes. So a standard-conforming
C++ compiler has no problem introducing such a constant, it is
/required/ to support this, provided it's supplied with the proper magic
incantation, and as mentioned above, why the committee didn't allow a
more natural and concise way to write that, well, politics, probably...
Enjoy (if u like pain!).
Cheers, & hth.,
- Alf