Optional function parameters: Use default arguments (NULL) or overload the function?

前端 未结 12 1557
情书的邮戳
情书的邮戳 2020-12-08 00:44

I have a function that processes a given vector, but may also create such a vector itself if it is not given.

I see two design choices for such a case, where a func

12条回答
  •  星月不相逢
    2020-12-08 01:16

    A references can't be NULL in C++, a really good solution would be to use Nullable template. This would let you do things is ref.isNull()

    Here you can use this:

    template
    class Nullable {
    public:
        Nullable() {
            m_set = false;
        }
        explicit
        Nullable(T value) {
            m_value = value;
            m_set = true;
        }
        Nullable(const Nullable &src) {
            m_set = src.m_set;
            if(m_set)
                m_value = src.m_value;
        }
        Nullable & operator =(const Nullable &RHS) {
            m_set = RHS.m_set;
            if(m_set)
                m_value = RHS.m_value;
            return *this;
        }
        bool operator ==(const Nullable &RHS) const {
            if(!m_set && !RHS.m_set)
                return true;
            if(m_set != RHS.m_set)
                return false;
            return m_value == RHS.m_value;
        }
        bool operator !=(const Nullable &RHS) const {
            return !operator==(RHS);
        }
    
        bool GetSet() const {
            return m_set;
        }
    
        const T &GetValue() const {
            return m_value;
        }
    
        T GetValueDefault(const T &defaultValue) const {
            if(m_set)
                return m_value;
            return defaultValue;
        }
        void SetValue(const T &value) {
            m_value = value;
            m_set = true;
        }
        void Clear()
        {
            m_set = false;
        }
    
    private:
        T m_value;
        bool m_set;
    };
    

    Now you can have

    void foo(int i, Nullable &optional = Nullable()) {
       //you can do 
       if(optional.isNull()) {
    
       }
    }
    

提交回复
热议问题