I am using a function (TinyXML's TiXmlElement::QueryValueAttribute(const std::string &name, T * outValue
) that attempts to read a string into the data type that is passed. In my case I am passing a bool
. So I want to use the boolalpha
flag so that the input can be true
or false
instead of 0
or 1
.
How do I do this?
Thanks.
TiXmlElement::QueryValueAttribute
uses a std::istringstream
to parse the value. So, you can create a wrapper class around bool
that overloads operator >>
to always set boolalpha
before extraction:
class TinyXmlBoolWrapper
{
public:
TinyXmlBoolWrapper(bool& value) : m_value(value) {}
bool& m_value;
};
std::istream& operator >> (std::istream& stream, TinyXmlBoolWrapper& boolValue)
{
// Save the state of the boolalpha flag & set it
std::ios_base::fmtflags fmtflags = stream.setf(std::ios_base::boolalpha);
std::istream& result = stream >> boolValue.m_value;
stream.flags(fmtflags); // restore previous flags
return result;
}
...
bool boolValue;
TinyXmlBoolWrapper boolWrapper(boolValue);
myTinyXmlElement->QueryAttribute("attributeName", &boolWrapper);
// boolValue now contains the parsed boolean value with boolalpha used for
// parsing