Converting from a std::string to bool

前端 未结 14 2679
走了就别回头了
走了就别回头了 2020-12-25 09:51

What is the best way to convert a std::string to bool? I am calling a function that returns either \"0\" or \"1\", and I need a clean solution for turning this into a boole

14条回答
  •  滥情空心
    2020-12-25 10:18

    You could always wrap the returned string in a class that handles the concept of boolean strings:

    class BoolString : public string
    {
    public:
        BoolString(string const &s)
        :   string(s)
        {
            if (s != "0" && s != "1")
            {
                throw invalid_argument(s);
            }
        }
    
        operator bool()
        {
            return *this == "1";
        }
    }
    

    Call something like this:

    BoolString bs(func_that_returns_string());
    if (bs) ...;
    else ...;
    

    Which will throw invalid_argument if the rule about "0" and "1" is violated.

提交回复
热议问题