我正在使用一个函数(TinyXML 的 TiXmlElement::QueryValueAttribute(const std::string &name, T * outValue
)尝试将字符串读入传递的数据类型。在我的例子中我正在传递一个 bool
。所以我想使用 boolalpha
标志,以便输入可以是 true
或 false
而不是 0
或 1
。
我该怎么做?
谢谢。
最佳答案
TiXmlElement::QueryValueAttribute
使用 std::istringstream
来解析值。因此,您可以围绕 bool
创建一个包装类,重载 operator >>
以在提取之前始终设置 boolalpha
:
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
关于C++:使用 boolalpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4789193/