In C# I can write something like this:
class AnyThing<T>
{
static public T Default = default(T);
}
static void Main ()
{
int i = AnyThing<int>.Default;
Console.WriteLine (i==0);
string s = AnyThing<string>.Default;
Console.WriteLine (s == null);
}
I intend to write a dictionary like template class in C++, I’d like the dict to return the default value (zero out) of the generic TVal type if the given key not be found. In C# the default(T) construct comes to rescue, while in C++ I’m not sure what is the appropriate way to do the same thing.
I’ve tried T obj = {} and T* obj = {} with gcc4.7, it works well. I’m just not so sure if it is the syntax defined by the language specification, if this kinda code will be portable cross compilers and platforms. Please help me with my doudt! Thanks in advance!
PS:
~~~~~~~~~~
To make sure the template get the default(zero out) value of ANY type, even of those that don’t have callable default ctor, I employed following mechanism (inspired by avakar’s answer):
template<class T>
struct AnyThing
{
static const T& Default ;
private:
static const char temp[sizeof(T)];
};
template<class T> const char AnyThing<T>::temp[] = {};
template<class T> const T& AnyThing<T>::Default = *(T*)temp;
struct st
{
double data;
st()=delete;
};
int main()
{
cout << (int)AnyThing<char*>::Default<<endl; //0
cout << AnyThing<int>::Default<<endl; //0
cout <<AnyThing<st>::Default.data<<endl; //0
}
It looks ugly, but shouldn’t cause any trouble, after all a zeroed out object is just a chunk of blank memory. Am I wrong?
In C++ there is no something like
defaultkeyword in C#. Since initialization by default constructor of value of class-type will be failed, if default constructor isprivate. In C#, if default constructor is private, value of class-type will be initialized tonull, since class-type isreference-type.Initialition by
{}is defined by language specification. It’s C++11. In C++03 you should useAs pointed by bames53 in comment, when you want to initialize
T*you should usebefore C++11.
or
in C++11.
or