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

前端 未结 12 1553
情书的邮戳
情书的邮戳 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:13

    Generally I agree with others' suggestion to use a two-function approach. However, if the vector created when the 1-parameter form is used is always the same, you could simplify things by instead making it static and using a default const& parameter instead:

    // Either at global scope, or (better) inside a class
    static vector default_vector = populate_default_vector();
    
    void foo(int i, std::vector const& optional = default_vector) {
        ...
    }
    

提交回复
热议问题