How to get the default value of any type

后端 未结 4 1684
难免孤独
难免孤独 2021-02-08 07:47

In C# I can write something like this:

    class AnyThing
    {
        static public T Default = default(T);
    }

    static void Main ()
    {
              


        
4条回答
  •  伪装坚强ぢ
    2021-02-08 08:11

    ForEveR's answer will not work if T doesn't have a copy constructor. In C++03, there is no way to zero-initialize a variable that is both generic and elegant. All that's left is the following trick.

    T temp[1] = {};
    T & obj = temp[0];
    

    Here, temp[0] is zero-initialized and then bound to obj. No copy constructors are needed.

提交回复
热议问题