【问题标题】:C# style enums in C++C++ 中的 C# 样式枚举
【发布时间】:2013-04-09 00:34:54
【问题描述】:

我正在尝试编写一个使用外部工具的日志库

我正在寻找一种方便的方法来将 Key-strings 添加到输出流中,以帮助外部工具进行解析,同时对使用该库的程序员的影响最小

目标是实现这样的目标:

cout << DEBUG::VERBOSE << "A should equal 3" << endl;
cout << DEBUG::WARNING << "something went wrong" << endl;

现在我的数据结构如下

struct Debug
{
static const std::string FATAL_ERROR; 
static const std::string ERROR;
static const std::string WARNING;
static const std::string IMPORTANT;
static const std::string INFORMATION;
static const std::string VERBOSE;
static const std::string DEBUG;
};

这很有效,但我想从std::string 类型中添加一个抽象级别。

在 Java/C# 中,我可以使用 enum 来实现写入行为,我如何在 C++ 中优雅地实现这一点。

【问题讨论】:

  • 避免非 POD 类型的静态变量(包括 std::string)。虽然它们现在可以工作,但您以后可能会遇到静态初始化问题的噩梦。
  • 这是这个问题目的的一部分:)

标签: c++ design-patterns iostream abstraction


【解决方案1】:

我认为在 C++ iostreams 中,endl 风格的流操作符更符合习惯:

#include <iostream>

namespace debug
{
    std::ostream & info(std::ostream & os) { return os << "Info: "; }
    std::ostream & warn(std::ostream & os) { return os << "Warning: "; }
    std::ostream & error(std::ostream & os) { return os << "Error: "; }
}

int main()
{
    std::cout << debug::info << "This is main()\n"
              << debug::error << "Everything is broken\n";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多