gpt4 book ai didi

静态成员函数中静态变量的 C++ 作用域

转载 作者:太空宇宙 更新时间:2023-11-04 13:57:19 25 4
gpt4 key购买 nike

我有一个进行一些解析的简单对象。在内部,有一个解析函数,包含一个静态变量,用于限制向用户打印错误消息的数量:

struct CMYParsePrimitive {
static bool Parse(const std::string &s_line)
{
// do the parsing

static bool b_warned = false;
if(!b_warned) {
b_warned = true;
std::cerr << "error: token XYZ is deprecated" << std::endl;
}
// print a warning about using this token (only once)

return true;
}
};

现在这些解析原语在类型列表中传递给解析器特化。还有一些其他接口(interface)告诉解析器应使用哪些解析原语解析哪些 token 类型。

我的问题是警告应该在每次应用程序运行时最多显示一次。但就我而言,它有时会显示多次,似乎是针对每个解析器实例而不是应用程序实例。

我使用的是 Visual Studio 2008,我想这可能是一些错误或偏离标准?有谁知道为什么会发生这种情况?

最佳答案

我没注意到函数也是一个模板。我的错。它在代码中使用不同的参数实例化了两次 - 因此警告有时会打印两次。真正的代码看起来更像这样:

struct CMYParsePrimitive {
template <class CSink>
static bool Parse(const std::string &s_line, CSink &sink)
{
// do the parsing, results passed down to "sink"

static bool b_warned = false;
if(!b_warned) {
b_warned = true;
std::cerr << "error: token XYZ is deprecated" << std::endl;
}
// print a warning about using this token (only once)

return true;
}
};

然后有例如CMYParsePrimitive::Parse<PreviewParser>::b_warned , 当 PreviewParser 使用时可以打印一次警告, 然后还有 CMYParsePrimitive::Parse<Parser>::b_warned Parser 使用时可以打印警告.

关于静态成员函数中静态变量的 C++ 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com