如果未调用特定函数,C++ 中是否有禁止代码编译的方法。
假设我有一些类(class):
class CExample
{
public:
void Init();
void DoWork();
};
如果没有为类对象调用 Init() 函数,是否有办法禁止调用 DoWork()?
我想禁止写这样的代码:
CExample e;
e.DoWork();
并允许这个版本:
CExample e;
e.Init();
e.DoWork();
我能否通过元编程以某种方式达到这种行为?
最佳答案
您可以只使用构造函数而不是 Init
。
在他的notes about exception safety in the standard library, as appendix to the 3rd edition of The C++ Programming Language , Bjarne Stroustrup 讨论了如何使用 init
函数与类不变性的概念不一致。这通常是 Bad Practice™,主要是出于这个原因。
一些旧的 GUI 框架(如 Microsoft 的 MFC)使用 init
函数来执行派生类特定的初始化。有other techniques to do that ,仅包括 passing the required information up the construction chain通过参数。
关于c++ - 如果未调用某些函数,则禁止代码编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588622/