What should the return type be when the function might not have a value to return?

后端 未结 6 1028
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 17:25

In the old days, you might have a function like this:

const char* find_response(const char* const id) const;

If the item could not be found

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 17:43

    boost::optional. It was specifically designed for this kind of situation.

    Note, it will be included in upcoming C++14 standard as std::optional. Update: After reviewing national body comments to N3690, std::optional was voted out from C++14 working paper into a separate Technical Specification. It is not a part of the draft C++14 as of n3797.

    Compared to std::unique_ptr, it avoids dynamic memory allocation, and expresses more clearly its purpose. std::unique_ptr is better for polymorphism (e.g. factory methods) and storing values in containers, however.

    Usage example:

    #include 
    #include 
    #include 
    
    class A
    {
    private:
        std::string value;
    public:
        A(std::string s) : value(s) {}
    
        boost::optional find_response(const std::string& id) const
        {
            if(id == value)
                return std::string("Found it!");
            else
                return boost::none;
            //or
            //return boost::make_optional(id == value, std::string("Found it!"));
        }
    
        //You can use boost::optional with references,
        //but I'm unfamiliar with possible applications of this.
        boost::optional get_id() const
        {
            return value;
        }
    };
    
    #include 
    
    int main()
    {
        A a("42");
        boost::optional response = a.find_response("42"); //auto is handy
        if(response)
        {
            std::cout << *response;
        }
    }
    

提交回复
热议问题