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

后端 未结 6 1026
被撕碎了的回忆
被撕碎了的回忆 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 18:09

    There are several good solutions here already. But for the sake of completeness I'd like to add this one. If you don't want to rely on boost::optional you may easily implement your own class like

    class SearchResult
    {
        SearchResult(std::string stringFound, bool isValid = true)
            : m_stringFound(stringFound),
            m_isResultValid(isValid)
        { }
    
        const std::string &getString() const { return m_stringFound; }
        bool isValid() const { return m_isResultValid; }
    
    private:
        std::string m_stringFound;
        bool m_isResultValid;
    };
    

    Obviously your method signature looks like this then

    const SearchResult& find_response(const std::string& id) const;
    

    But basically that's the same as the boost solution.

提交回复
热议问题