Re: static const class member difficulties...style?
* todma:
I'm re-writing #defines to be class Static Const members.... Alot of
them are not ints or enum.
(I assume allowing int and enum to be initialized in the class
definition is an optimization?)...
It is an optimization supported by the standard. It's not primarily an
optimization of execution speed, but of convenience and programmer's
time. However, since it supports header-only libraries, it can have the
opposite effect, increasing programmer's time (longer coffee breaks).
#define BackColor RGB(0,0,0)
Is Now....
//.h
class Cthing
{
static const COLORREF myBackColor;
};
//.cpp
#include "Cthing.h"
COLORREF Cthing::myBackColor = RGB(0,0,0);
Old Way:
Many of my classes just use .h files, and don't have .cpp files. They
are small, and I think having .cpp files when unnecessary is a waste.
I have a problem, which is that I am including my (old) .h files in
different .cpp projects (modules).
So Now....
I have to have a global .cpp file to initialize the more complex
static const variables...And this global CPP file now must be included
in different projects so that the values are the same?
What am I missing? Should I go back to using #define and just forget
about it?
Assuming RGB is a macro that expands to an expression with compile time
evaluation, and that COLORREF is an integral type, you could have
written the above simply as
class CThing
{
static COLORREF const theBackColor = RGB( 0,0,0 );
public:
...
};
or with an older compiler not supporting that, used an 'enum'.
If what you mean by "more complex" can be exemplified by RGB expanding
to or being a function, and/or that COLORREF is not an integral type,
you could have written the above in the header file as
namespace CThingConstant
{
static COLORREF const backColor = RGB( 0, 0, 0 );
}
if you're happy with a potential copy in every translation unit.
Or, if you want just one instance of the constant in the whole program,
and/or better access control, then you could have written it in the
header file as
template< typename Dummy >
struct CThingConstants_
{
static COLORREF const backColor;
};
template< typename Dummy >
COLORREF CThingConstants_<Dummy>::backColor = RGB( 0, 0, 0 );
class CThing: private CThingConstants_<void>
{
public:
...
};
This latter method, which probably should have a name (even if I'm the
only one pushing it, and don't use it myself!), corresponds to 'inline'
for functions, except that C++ unfortunately doesn't support the keyword
'inline' for data -- in spite of the machinery being in place (the
above works, supported by the standard).
Disclaimer: off-the-cuff code, untouched by compiler's hands.
Hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]