No, it should create a non-constant variable and then when you hand it a value it becomes constant, in theory. I just finished the template version and it works!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
template <class T>
class lockvar
{
public:
lockvar() { locked = false; }
void set(T varType_)
{
if (!locked)
{
varType = varType_;
locked = true;
}
}
T get() { return varType; }
protected:
bool locked;
T varType;
};
|
So if I wanted to make the application handle and device context global which is sort of handy but I don't want any part of my program attempting to change it, I do this.
1 2 3 4 5
|
lockvar<HWND> g_hWnd; // variable declared can still be changed.
lockbar<HDC> g_HDC; // variable declared can still be changed.
g_hWnd.set(what ever returns an application handle 'hWnd'); // now set and cannot be changed.
g_HDC = GetDC(g_hWnd.get()); // get value from g_hWnd!
|
The idea is you call the set() function only once, after it executes the first time, it sets locked too true, before settig the variable type, it checks to see if it is locked, if it is, it doesn't do anything which, is the intended design...of course, you could always make it return some type of error, so I guess it still needs a bit of work.
I tried overloading the = operator so that I could do this...
1 2 3
|
lockvar<HWND> g_hWnd;
g_hWnd = what ever returns a window handle here;
|
Didn't work the way I wanted it too or maybe I just don't know how to do it. If I can make the = operator assign the value and make the class store it inside its own variable varType, that would be awesome but then how do we get the value out?
|
somefunction(g_hWnd,whatever);
|
The above just seems impossible, since g_hWnd is some sort of type, how could you make it return the value it has stored if only g_hWnd is specified.....lol what i'm thinking and trying to do right now might not be possible in C++ at all, altho, there are clever people out there!