c++ - 关于 'C++ Coding Standards' 书中的最佳实践和宏的问题

标签 c++ macros coding-style

摘自 Herb Sutter 和 Andrei Alexandrescu 的“C++ 编码标准”,第 16 项:在本指南的异常(exception)情况下避免使用宏,他们写道:

For conditional compilation (e.g., system-dependent parts), avoid littering your code with #ifdefs. Instead, prefer to organize code such that the use of macros drives alternative implementations of one common interface, and then use the interface throughout.

我无法准确理解他们的意思。如何在不使用 #ifdef 条件编译宏指令的情况下驱动替代实现?有人可以提供一个例子来帮助说明上一段所提出的内容吗?

谢谢

最佳答案

他们的意思是,您应该通过使用抽象基类从系统相关部分中抽象出代码,并仅在实例化时使用条件编译。

class SystemAgnosticInterface
{
public:
    virtual ~SystemAgnosticInterface() {}
    virtual void doStuff() = 0;
};

然后,例如,您可以拥有特定于 Windows 和 Linux 的接口(interface)实现(每个接口(interface)仅包含在其关联平台的编译中),例如使用:

SystemAgnosticInterface *createFoo()
{
#ifdef _WIN32
    return new WindowsImplementation;
#else
    return new LinuxImplementation;
#endif
}

int main()
{
    SystemAgnosticInterface *foo = createFoo();
    foo->doStuff(); // No conditional compilation here
    delete foo;
}

这显然是一个过于简化的代码示例,但我希望您能理解这一点:这并不是要完全避免 #ifdef,只是它们不应该使代码的每个部分变得困惑。

关于c++ - 关于 'C++ Coding Standards' 书中的最佳实践和宏的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4633879/

相关文章:

c - 使用#ifndef#define #endif 处理 C 头文件的最佳实践

c++ - 将 boost::multi precision::mpq_rational 舍入到最接近的整数

c++ - 无论如何在 C++ 中的特定条件下定义/运行宏?

scala - 在宏中使用私有(private)构造函数

c - 使用 C 预处理器进行嵌套宏迭代

Java 代码约定 : must match pattern '^[a-z][a-zA-Z0-9]*$'

c++ - 作为参数传递给函数(c++)时如何修改全局结构?

c++ - 使用 C++ 时程序与数据库的连接

c++ - RAII 是什么时候添加到 C++ 中的

Python:在方法之间传递变量时,是否需要为其指定一个新名称?