C++: automatic initialization - c++

I find it sometimes annoying that I have to initialise all POD-types manually. E.g.
struct A {
int x;
/* other stuff ... */
A() : x(0) /*...*/ {}
A(/*..*/) : x(0) /*...*/ {}
};
I don't like this for several reasons:
I have to redo this in every constructor.
The initial value is at a different place than the variable declaration.
Sometimes the only reason I have to implement a constructor is because of this.
To overcome this, I try to use my own types instead. I.e. instead of using int x,y;, I use my own vector struct which also initialize automatically with 0. I also thought about just implementing some simple wrapper types, like:
template<typename T>
struct Num {
T num;
Num() : num(0) {}
operator T&() { return num; }
operator const T&() const { return num; }
T& operator=(T _n) { num = _n; return num; }
/* and all the other operators ... */
};
This basically solves this so far for all cases where I want to init with 0 (that are by far the most often cases for me).
Thanks to James McNellis for the hint: This can also be solved via the boost::value_initialized.
Now, not limited to POD-types:
But sometimes I want to initialise with something different and there are the troubles again because that Num template struct cannot easily be extended to allow that. Basically because I cannot pass floating point numbers (e.g. float) as a template parameter.
In Java, I would just do:
class A {
int x = 42;
/*...*/
public A() {}
public A(/*...*/) { /*...*/ }
public A(/*...*/) { /*...*/ }
/*...*/
}
I find it quite important that in such cases where you want to init a member variable always in the same way in all possible constructors, that you are able to write the init value directly next to the member variable, like in int x = 42;.
So the thing I was trying to solve is to do the same thing in C++.
To overcome the problem that I cannot pass the init-value via a template parameter, I hacked together an ugly macro:
#define _LINENAME_CAT( name, line ) name##line
#define _LINENAME( name, line ) _LINENAME_CAT( name, line )
/* HACK: use _LINENAME, workaround for a buggy MSVC compiler (http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=360628)*/
#define PIVar(T, def) \
struct _LINENAME(__predef, __LINE__) { \
typedef T type; \
template<typename _T> \
struct Data { \
_T var; \
Data() : var(def) {} \
}; \
Data<T> data; \
T& operator=(const T& d) { return data.var = d; } \
operator const T&() const { return data.var; } \
operator T&() { return data.var; } \
}
(For other compilers, I can just omit that _LINENAME name for the struct and just leave it unnamed. But MSVC doesn't like that.)
This now works more or less like I want it. Now it would look like:
struct A {
PIVar(int,42) x;
/*...*/
A() {}
A(/*...*/) { /*...*/ }
A(/*...*/) { /*...*/ }
/*...*/
};
While it does what I want (mostly), I still am not fully happy with it:
I don't like the name PIVar (which stands for PreInitVar) but I really couldn't come up with something better. At the same time, I want to have it short.
I don't like that macro hack.
How have you solved this? Any better solution?
There was an answer which was deleted again which said that C++0x allows basically the same syntax as in Java. Is that true? So then I would just have to wait for C++0x.
Please don't give any comments like:
"then just use Java instead" / "don't use C++ then" or
"if you need something like this, you are probably doing something wrong" or
"just don't do it this way".
Also, please don't tell me not to use it. I know about all the drawbacks of my current solution. Please only make comments about non-obvious drawbacks if you are really sure that I am not aware of that. Please don't just state that there are many drawbacks in my current solution. Please also don't state that it is not worse to use it. I am just asking if you know about a better solution than the one I have presented here.

Sometimes the only reason I have to implement a constructor is because of this.
You don't have to do that.
struct POD {
int i;
char ch;
};
POD uninitialized;
POD initialized = POD();
Equally in an initialization list:
class myclass
POD pod_;
// ....
myclass()
: pod_() // pod_'s members will be initialized
{
}
To overcome this, I try to use my own types instead.
Your type fails in this scenario:
void f(int&);
Num<int> i;
f(i);
There's likely more problems, but this is what occurred to me immediately.
How have you solved this? Any better solution?
Yes, we all have solved this. We did by not attempting to fight the language, but to use it the way it was created: initialize PODs in initialization lists. When I see this:
struct ML_LieroX : MapLoad {
std::string id;
PIVar(int, 0) type;
std::string themeName;
PIVar(int, 0) numObj;
PIVar(bool,false) isCTF;
I cringe. What is this doing? Why is it this way? Is this even C++?
All this just to save a few keystrokes typing an initialization list? Are you even serious?
Here's an old bon mot: A piece of code gets written once, but over its lifetime will be read tens, hundreds, or even thousands of times. That means that, in the long run, the time it takes to write a piece code is more or less neglectable. Even if it takes you ten times as long to write the proper constructors, but it saves me 10% of the time necessary to understand your code, then writing the constructors is what you should do.

Boost provides a value_initialized<T> template that can be used to ensure an object (POD or not) is value-initialized. Its documentation goes into great detail explaining the pros and cons of using it.
Your complaint about not being able to automatically initialize an object to a given value doesn't make much sense; that has nothing to do with the object being POD; if you want to initialize a non-POD type with a non-default value, you have to specify the value when you initialize it.

You could initialize POD structures as follows:
struct POD
{
int x;
float y;
};
int main()
{
POD a = {}; // initialized with zeroes
POD b = { 1, 5.0f }; // x = 1, y = 5.0f
return 0;
}

There is a proposal for C++0x which allows this:
struct A {
int x = 42;
};
That is exactly what I want.
If this proposal is not making it into the final version, the possibility of delegating constructors is another way of at least avoiding to recode the initialization in every single constructor (and at the same time avoiding a dummy helper function to do this).
In current C++, there does not seem to be any better way to do it despite what I have already demonstrated.

C++ does have constructor delegation, so why not use it?
struct AState
{
int x;
AState() : x(42) {}
};
class A : AState
{
A() {}
A(/*...*/) { /*...*/ }
A(/*...*/) { /*...*/ }
};
Now initialization of x is delegated by all constructors. The base constructor can even accept arguments passed from each version of A::A.

Prior to C++0x there is a solution which works well if the non-zero value you want to initialize with is not completely arbitrary (which is usually the case in practice). Similar to boost::initialized_value but with an extra argument to take the initial value (which gets a little fussy because C++).
template<typename T> struct Default { T operator()() { return T(); } };
template<typename T, T (*F)()> struct Call { T operator()() { return F(); } };
template<int N> struct Integer { int operator()() { return N; } };
template< typename X, typename Value = Default<X> >
class initialized {
public:
initialized() : x(Value()()) {}
initialized(const X& x_) : x(x_) {}
const X& get() const { return x; }
operator const X&() const { return x; }
operator X&() { return x; }
private:
X x;
};
You might use it like this:
struct Pi { double operator()() { return 3.14; } }; //Exactly
const char* init_message() { return "initial message"; }
Point top_middle() { return Point(screen_width()/2, 0); }
struct X {
initialized<int> a;
initialized<int, Integer<42> > b;
initialized<double> c;
initialized<double, Pi> d;
initialized<std::string> e;
initialized<std::string, Call<const char*, init_message> > f;
initialized<Point> g;
initialized<Point, Call<Point,top_middle> > h;
X() {}
};
I find the annoyance of having to create a dummy function to return any non-integral / non-default value is generally amortized across the entire library (since the non-zero initial values for a particular type are generally shared by many classes).
Obviously typedef is a friend here.
Anyway, can't wait to upgrade to C++0x/11/14/whatever.

Related

How to initialise explicit constructor in array initialiser list? [duplicate]

A library which I can't modify has a type akin to the following:
class A {
public:
A () : A(0) { }
explicit A (int const value) : value_(value) { }
A (A const &) = delete;
A (A &&) = delete;
A & operator= (A const &) = delete;
A & operator= (A &&) = delete;
private:
int value_;
}
Now, I have a class which requires a bunch of As as members. Due to other restrictions of the environment I'm working in all of these As must either be separate members or a member array (i.e. I can't use an std::vector to put them in or create pointers to them). I.e. my class boils down to this:
struct Foo {
A a[2];
}
Is there any way to initialize each member with a distinct initial value? I've been trying various forms of using braced-list initialization, but they all fail due to either A(int) being explicit or A not having a copy/move-constructor.
What doesn't work:
Foo () : A{ { 1 }, { 2 } } { }: won't call A(int) since it's explicit.
Foo () : A{ { A(1) }, { A(2) } } { }: can't copy- nor move-assign.
Edit: Updated info about member array requirement.
Edit 2: The library in question is SystemC. My example class A is a port (e.g. sc_core::sc_in).
The reason I can't use an array of pointers is because, as far as I know, Mentor Graphic's Questa can't really deal with them. It will simulate the model correctly, but won't allow inspection of the ports. I.e. it won't be able to plot the port's values over time in a wave window. I would be very happen to be proven wrong about this, because that would allow a trivial solution to my problem.
Edit 3: Apparently this is a big issue anymore in a newer version of Questa. I'm not sure what changed between seeing this problem and now, could be a change to the development environment as well (which is also out of my control). In any case, my Questa now automatically names ports after their variable name (unless explicitly renamed at construction), so all is well.
Just for the sake knowing how to I'd still like to see potential solutions to the original problem though.
struct Foo {
A a[2];
}
Is there any way to initialize each member with a distinct initial
value? I've been trying various forms of using braced-list
initialization, but they all fail due to either A(int) being
explicit or A not having a copy/move-constructor.
You may need to use placement-new to create an array of A in some raw storage array. You then create a std::initializer_list<ARGUMENT> of the ARGUMENTs needed to construct each A. Something like:
template<typename T, std::size_t Size, std::size_t Alignment = alignof(T)>
struct FixedArray{
std::aligned_storage_t<sizeof(T), Alignment> data[Size];
static constexpr std::size_t size = Size;
template<typename U>
FixedArray(std::initializer_list<U> ls){
assert(ls.size() <= Size && "Invalid Size"); int index = 0;
for(auto& x : ls)
new (&data[index++]) T(x);
}
FixedArray(const FixedArray&) = delete;
FixedArray(FixedArray&&) = delete;
A& operator[](std::size_t index){
auto ptr = reinterpret_cast<A*>(&data) + index;
return *std::launder(ptr); //Sort of a legal way to alias memory C++17
}
~FixedArray(){
for(std::size_t i = 0; i < size; i++)
this->operator[](i).~T();
}
};
Then declare Foo:
struct Foo {
FixedArray<A, 4> a;
};
To create Foo having A(546), A(99), A(-4), A(0):
int main() {
Foo f{{546, 99, -4, 0}};
return 0;
}
See a working Demo
After testing with GCC 6.3 at -O3 optimization levels, about exactly the same assembly is generated for using FixedArray vs plain raw arrays, See it on gcc.godbolt.com.
I am able to solve the problem as follows (also using SystemC, here my non-copyable, non-movable items are sc_modules):
class Object : sc_module {
Object(sc_module_name name){}
};
class Container : sc_module {
std::array<Object, 3> objects;
Container(sc_module_name name) :
objects{{{"object1"},{"object2"},{"object3"}}}
{}
};
The short answer - no. The longer answer - kind of, but its disgusting.
Take a look at this discussion.

Initialization of member array of non-copyable, non-movable, explicitly constructed types

A library which I can't modify has a type akin to the following:
class A {
public:
A () : A(0) { }
explicit A (int const value) : value_(value) { }
A (A const &) = delete;
A (A &&) = delete;
A & operator= (A const &) = delete;
A & operator= (A &&) = delete;
private:
int value_;
}
Now, I have a class which requires a bunch of As as members. Due to other restrictions of the environment I'm working in all of these As must either be separate members or a member array (i.e. I can't use an std::vector to put them in or create pointers to them). I.e. my class boils down to this:
struct Foo {
A a[2];
}
Is there any way to initialize each member with a distinct initial value? I've been trying various forms of using braced-list initialization, but they all fail due to either A(int) being explicit or A not having a copy/move-constructor.
What doesn't work:
Foo () : A{ { 1 }, { 2 } } { }: won't call A(int) since it's explicit.
Foo () : A{ { A(1) }, { A(2) } } { }: can't copy- nor move-assign.
Edit: Updated info about member array requirement.
Edit 2: The library in question is SystemC. My example class A is a port (e.g. sc_core::sc_in).
The reason I can't use an array of pointers is because, as far as I know, Mentor Graphic's Questa can't really deal with them. It will simulate the model correctly, but won't allow inspection of the ports. I.e. it won't be able to plot the port's values over time in a wave window. I would be very happen to be proven wrong about this, because that would allow a trivial solution to my problem.
Edit 3: Apparently this is a big issue anymore in a newer version of Questa. I'm not sure what changed between seeing this problem and now, could be a change to the development environment as well (which is also out of my control). In any case, my Questa now automatically names ports after their variable name (unless explicitly renamed at construction), so all is well.
Just for the sake knowing how to I'd still like to see potential solutions to the original problem though.
struct Foo {
A a[2];
}
Is there any way to initialize each member with a distinct initial
value? I've been trying various forms of using braced-list
initialization, but they all fail due to either A(int) being
explicit or A not having a copy/move-constructor.
You may need to use placement-new to create an array of A in some raw storage array. You then create a std::initializer_list<ARGUMENT> of the ARGUMENTs needed to construct each A. Something like:
template<typename T, std::size_t Size, std::size_t Alignment = alignof(T)>
struct FixedArray{
std::aligned_storage_t<sizeof(T), Alignment> data[Size];
static constexpr std::size_t size = Size;
template<typename U>
FixedArray(std::initializer_list<U> ls){
assert(ls.size() <= Size && "Invalid Size"); int index = 0;
for(auto& x : ls)
new (&data[index++]) T(x);
}
FixedArray(const FixedArray&) = delete;
FixedArray(FixedArray&&) = delete;
A& operator[](std::size_t index){
auto ptr = reinterpret_cast<A*>(&data) + index;
return *std::launder(ptr); //Sort of a legal way to alias memory C++17
}
~FixedArray(){
for(std::size_t i = 0; i < size; i++)
this->operator[](i).~T();
}
};
Then declare Foo:
struct Foo {
FixedArray<A, 4> a;
};
To create Foo having A(546), A(99), A(-4), A(0):
int main() {
Foo f{{546, 99, -4, 0}};
return 0;
}
See a working Demo
After testing with GCC 6.3 at -O3 optimization levels, about exactly the same assembly is generated for using FixedArray vs plain raw arrays, See it on gcc.godbolt.com.
I am able to solve the problem as follows (also using SystemC, here my non-copyable, non-movable items are sc_modules):
class Object : sc_module {
Object(sc_module_name name){}
};
class Container : sc_module {
std::array<Object, 3> objects;
Container(sc_module_name name) :
objects{{{"object1"},{"object2"},{"object3"}}}
{}
};
The short answer - no. The longer answer - kind of, but its disgusting.
Take a look at this discussion.

Enforce function calls at compile time in C++

Is there a way in C++ to enforce function calls in compile time in such a way that this call will be allowed:
obj.reset().setParam1(10).setParam2(20);
but this one will fail to compile:
obj.reset().setParam1(10);
I want to avoid setting all parameters in one function since there are too many to be set; so I prefer to use something similar to named parameters idiom.
EDIT: Alternative syntax could be:
obj.reset(setParam1(10), setParam2(20));
or
obj.reset(setParam1(10).setParam2(20));
As the desired behaviour must be present at compile time, it needs to be implemented within the type system. To my understanding, this is impossible in C++ - the named parameters idiom relies on setter functions having the same return type (namely the type of the object which is called on), so calls to certain methods cannot be prevented.
I'll give you an example of doing that with the 2 parameters you provide, if you need more, it needs more work. If the requirement hierarchy between parameters get too complex, you may find it hard to structure your classes but here it goes:
class Obj {
Obj2 setParam2(int v);
}
class Obj2: public Obj {
Obj2 setParam1(int v);
}
int main() {
Obj obj;
obj.setParam2(10); // possible
obj.setParam2(10).setParam1(20); // possible
obj.setParam1(20); // not possible
obj.setParam1(20).setParam2(10); // unfortunately not possible
// Edit: one more limitation- consecutive calls are not possible,
// you must chain
obj.setParam2(20);
obj.setParam1(10); // problem
}
The best thing I could do to provide both named parameters and enforce all of them being initialized is this.
template<typename T>
struct Setter
{
Setter(const T &param) : ref(param) {}
const T &ref;
};
typedef Setter<int> Param1;
typedef Setter<std::string> Param2;
struct CObj
{
void reset(const Param1 &A, const Param2 &B) {
setParam1(A.ref); setParam2(B.ref); }
void setParam1(int i) { param1 = i; }
void setParam2(const std::string &i) { param2 = i; }
int param1;
std::string param2;
};
int main()
{
CObj o;
o.reset(Param1(10), Param2("hehe"));
}

How to do the equivalent of memset(this, ...) without clobbering the vtbl?

I know that memset is frowned upon for class initialization. For example, something like the following:
class X { public:
X() { memset( this, 0, sizeof(*this) ) ; }
...
} ;
will clobber the vtbl if there's a virtual function in the mix.
I'm working on a (humongous) legacy codebase that is C-ish but compiled in C++, so all the members in question are typically POD and require no traditional C++ constructors. C++ usage gradually creeps in (like virtual functions), and this bites the developers that don't realize that memset has these additional C++ teeth.
I'm wondering if there is a C++ safe way to do an initial catch-all zero initialization, that could be followed by specific by-member initialization where zero initialization isn't appropriate?
I find the similar questions memset for initialization in C++, and zeroing derived struct using memset. Both of these have "don't use memset()" answers, but no good alternatives (esp. for large structures potentially containing many many members).
For each class where you find a memset call, add a memset member function which ignores the pointer and size arguments and does assignments to all the data members.
edit:
Actually, it shouldn't ignore the pointer, it should compare it to this. On a match, do the right thing for the object, on a mismatch, reroute to the global function.
You could always add constructors to these embedded structures, so they clear themselves so to speak.
Try this:
template <class T>
void reset(T& t)
{
t = T();
}
This will zeroed your object - no matter it is POD or not.
But do not do this:
A::A() { reset(*this); }
This will invoke A::A in infinite recursion!!!
Try this:
struct AData { ... all A members };
class A {
public:
A() { reset(data); }
private:
AData data;
};
This is hideous, but you could overload operator new/delete for these objects (or in a common base class), and have the implementation provide zero'd out buffers. Something like this :
class HideousBaseClass
{
public:
void* operator new( size_t nSize )
{
void* p = malloc( nSize );
memset( p, 0, nSize );
return p;
}
void operator delete( void* p )
{
if( p )
free( p );
}
};
One could also override the global new/delete operators, but this could have negative perf implications.
Edit: I just realized that this approach won't work for stack allocated objects.
Leverage the fact that a static instance is initialised to zero:
https://ideone.com/GEFKG0
template <class T>
struct clearable
{
void clear()
{
static T _clear;
*((T*)this) = _clear;
};
};
class test : public clearable<test>
{
public:
int a;
};
int main()
{
test _test;
_test.a=3;
_test.clear();
printf("%d", _test.a);
return 0;
}
However the above will cause the constructor (of the templatised class) to be called a second time.
For a solution that causes no ctor call this can be used instead: https://ideone.com/qTO6ka
template <class T>
struct clearable
{
void *cleared;
clearable():cleared(calloc(sizeof(T), 1)) {}
void clear()
{
*((T*)this) = *((T*)cleared);
};
};
...and if you're using C++11 onwards the following can be used: https://ideone.com/S1ae8G
template <class T>
struct clearable
{
void clear()
{
*((T*)this) = {};
};
};
The better solution I could find is to create a separated struct where you will put the members that must be memsetted to zero. Not sure if this design is suitable for you.
This struct got no vtable and extends nothings. It will be just a chunk of data. This way memsetting the struct is safe.
I have made an example:
#include <iostream>
#include <cstring>
struct X_c_stuff {
X_c_stuff() {
memset(this,0,sizeof(this));
}
int cMember;
};
class X : private X_c_stuff{
public:
X()
: normalMember(3)
{
std::cout << cMember << normalMember << std::endl;
}
private:
int normalMember;
};
int main() {
X a;
return 0;
}
You can use pointer arithmetic to find the range of bytes you want to zero out:
class Thing {
public:
Thing() {
memset(&data1, 0, (char*)&lastdata - (char*)&data1 + sizeof(lastdata));
}
private:
int data1;
int data2;
int data3;
// ...
int lastdata;
};
(Edit: I originally used offsetof() for this, but a comment pointed out that this is only supposed to work on PODs, and then I realised that you can just use the member addresses directly.)

How not to compile casting into enum type in C++?

I have this "better" enum class that
cannot contain invalid values, and
cannot be used until enum value is not set explicitly,
as follows:
class Symmetry
{
public:
enum Type {
GENERAL, SYMMETRIC, HERMITIAN,
SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
};
Symmetry() { t_ = UNINITIALIZED }
explicit Symmetry(Type t) : t_(t) { checkArg(t); }
Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }
operator Type() const {
if (t_ == UNINITIALIZED) throw runtime_error("error");
return t_;
}
private:
Type t_;
void checkArg(Type t) {
if ((unsigned)t >= (unsigned)UNINITIALIZED)
throw runtime_error("error");
}
};
This allows me to write the following code:
Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws
My problem is that a compiler allows constructs such as:
Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws
I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?
Potentially a crummy solution, but it would solve your immediate problem. Rather than having an inner enum type, define a little helper class with a private constructor, and make the outer class a friend. Then the "enum" values can be static const members in your outer class. Something like this:
(DISCLAIMER: untested, so there may be various compilation issues, but you should get the idea)
class Symmetry
{
public:
class Type
{
private:
Type() {};
friend class Symmetry;
};
static const Type GENERAL;
static const Type SYMMETRIC;
static const Type HERMITIAN;
};
You will need some way of determining equality, but this should be fairly easy.
My attempt using templates: (tested. However, this can be further improved!)
template<int N>
struct Symmetry
{
enum Type
{
GENERAL, SYMMETRIC, HERMITIAN,
SKEW_SYMMETRIC, SKEW_HERMITIAN
};
template<Type e> struct allowed;
template<> struct allowed<GENERAL> { static const int value = GENERAL; };
template<> struct allowed<SYMMETRIC> { static const int value = SYMMETRIC; };
template<> struct allowed<HERMITIAN> { static const int value = HERMITIAN; };
template<> struct allowed<SKEW_SYMMETRIC> { static const int value = SKEW_SYMMETRIC; };
template<> struct allowed<SKEW_HERMITIAN> { static const int value = SKEW_HERMITIAN; };
allowed<(Type)N> m_allowed;
operator int()
{
return N;
}
};
Symmetry<0> e0; //okay
Symmetry<1> e1; //okay
Symmetry<100> e4; //compilation error!
Symmetry<e0.SKEW_HERMITIAN> e3; //okay
Symmetry<e0.SKEW_SYMMETRIC> e3; //okay
Usage:
int main()
{
Symmetry<0> e0;
Symmetry<e0.HERMITIAN> e1;
switch (e1)
{
case e0.HERMITIAN:
{
cout << "It's working" << endl;
}
break;
}
}
No. If you allow any cast to be used, as your last example does, then there will always be some cast that can be used to subvert your type.
The solution is to not be in the habit of using these casts and to very suspiciously consider any code that uses these casts indiscriminately. View this type of casting as the nuclear bomb in your arsenal: it's important to have, but you always handle it with care and never want to deploy it more than rarely.
What warning options does your compiler have for casting? What lint tools are you using which may detect this misuse of casts?
That said, it appears you really want to hide the inner Type so users are less tempted to even use it. Realizing that, it's straight-forward to make that type name private, even while not preventing all cast misuse, by slightly tweaking your original:
struct Symmetry {
enum {
UNINITIALIZED,
GENERAL, SYMMETRIC, HERMITIAN,
SKEW_SYMMETRIC, SKEW_HERMITIAN
};
private:
typedef decltype(UNINITIALIZED) Hidden;
Hidden _value;
public:
Symmetry(Hidden value = UNINITIALIZED) : _value (value) {}
Symmetry& operator=(Hidden value) { _value = value; return *this; }
operator Hidden() const {
if (_value == UNINITIALIZED) {
throw std::logic_error("uninitialized Symmetry");
}
return _value;
}
bool initialized() const { return _value != UNINITIALIZED; }
// required if you want to check for UNINITIALIZED without throwing in
// the above conversion
};
This is a complete implementation, no details omitted or unknown, or issues with initialization order. The only caveat is decltype – with a pre-C++0x compiler, you'll have to use something implementation-specific or a library which wraps something implementation-specific.
And a smaller issue: change from runtime_error to logic_error, as using uninitialized values should be preventable beforehand and thus falls in the latter category.