I find it sometimes annoying that I have to initialize all POD types manually. For instance.
struct A {
int x;
A() : x(0) {}
A() : x(0) {}
};
I do not like this for several reasons:
- I need to redo this in every constructor.
- The initial value is in a different place than the variable declaration.
- Sometimes because of this, the only reason that I have to implement the constructor arises.
To overcome this, I am trying to use my own types. That is, instead of using, int x,y;I use my own vector structure, which is also automatically initialized with 0. I also thought about just implementing some simple types of wrappers, for example:
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; }
};
, 0 ( ).
: boost::value_initialized.
, POD-:
- , , Num , . , (, float) .
Java :
class A {
int x = 42;
public A() {}
public A() { }
public A() { }
}
, , - , init -, , int x = 42;.
, ++.
, init , :
#define _LINENAME_CAT( name, line ) name##line
#define _LINENAME( name, line ) _LINENAME_CAT( name, line )
#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; } \
}
( _LINENAME . MSVC .)
, . :
struct A {
PIVar(int,42) x;
A() {}
A() { }
A() { }
};
, ( ), :
PIVar ( PreInitVar), - . , .- .
? ?
, , , ++ 0x , Java. ? ++ 0x.
, :
- ", Java " / ", ++ then"
- ", - , , , - "
- " ".
, , . . , , , . , , . , , . , , , .