How to get the default value of any type

后端 未结 4 1683
难免孤独
难免孤独 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:33

    Create your own default keyword:

    class default_t
    {
    public:
      template
      operator T() const { return T(); }
    };
    
    default_t const default = default_t();
    

    Use it like:

    int myInt = default;
    vector myVector = default;
    shared_ptr myPtr = default;
    

    Or with a slight semantic variation:

    default_t const empty = default_t();
    
    vector fetchPersons()
    {
      if (Database::isConnected())
      {
        return Database::fetchPersons();
      }
    
      return empty;
    }
    

提交回复
热议问题