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

标签 c++ static

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

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/

相关文章:

c# - 通用静态类 - 在运行时检索对象类型

c++ - 我如何在 C++ 中以编程方式确定 MTU

python - 通过 apache 提供静态文件

c++ - 获取磁盘转速示例代码

c++ - 如何在多线程的 OSX 上安装 XGBoost

Java 有 FindBugs。 Ruby 的等价物是什么?

c - 静态变量未被初始化

c++ - 为什么我不能在类中为静态变量设置值?

c++ - 在 cpp 文件中设置静态枚举变量的正确方法

c++ - BOOST_CHECK_CLOSE 失败输出的格式化?