摘自 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/