Re: static definiitions
LuB wrote:
I have written a library with only template .hpp files. OT but if it
helps, modelled after Microsoft's WTL or ATL library.
Now I'd like to create a class with nothing but constants. In this
case, it is simply a class of colors. The members should be static. Is
there a way to declare and define these in the same file (or spot)
without artificially creating a template.
I thought the following was illegal - or could pose problems down the
road - but it seems to compile just fine for me now. If this is legal -
then that is answer to my post.
It is legal as all the macros can be evaluated at compile time.
An alternative would be to use compile time templates. The following is
quite simple but, using something like boosts mpl :
http://www.boost.org/libs/mpl/doc/index.html
, you could do something much more sophisticated of course.
( The code only works in VC++ when windows extensions are turned on BTW
;-))
regards
Andy Little
#include <windows.h>
#include <iostream>
template <BYTE R,BYTE G, BYTE B>
struct static_rgb_color{
static const BYTE red = R;
static const BYTE green = G;
static const BYTE blue = B;
};
template <typename StaticRGBColor>
struct make_colorref{
static const COLORREF value
= (StaticRGBColor::red)
|(StaticRGBColor::green << 8 )
| (StaticRGBColor::blue << 16);
};
struct colors{
typedef static_rgb_color<0xff,0,0> red;
typedef static_rgb_color<0,0xff,0> green;
typedef static_rgb_color<0,0,0xff> blue;
typedef static_rgb_color<0xff,0xff,0xff> white;
typedef static_rgb_color<0x0,0x0,0x0> black;
template <typename Color> struct name;
};
template <>
struct colors::name<colors::red>{
const char* operator()(){return "red";}
};
template <>
struct colors::name<colors::green>{
const char* operator()(){return "green";}
};
template <>
struct colors::name<colors::blue>{
const char* operator()(){return "blue";}
};
template <>
struct colors::name<colors::white>{
const char* operator()(){return "white";}
};
template <>
struct colors::name<colors::black>{
const char* operator()(){return "black";}
};
template <typename Color>
void show_color_ref(){
std::cout << "COLORREF value for " << colors::name<Color>()() << "
= "
<< std::hex << make_colorref<Color>::value << '\n';
}
int main()
{
show_color_ref<colors::red>();
show_color_ref<colors::green>();
show_color_ref<colors::blue>();
show_color_ref<colors::black>();
show_color_ref<colors::white>();
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]