c++ - 如果未调用某些函数,则禁止代码编译

标签 c++ templates c++11 metaprogramming

如果未调用特定函数,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/

相关文章:

c++ - 取消引用指针(并返回它)的问题

c++ - 哈希函数为一对long long?

c++ - 简单的 C++ 继承示例,有什么问题?

c++ - OpenCL。矩阵乘法绕过一些工作项

c++ - 将argpack分成两半?

c++ - 如何声明模板模板参数

c++ - 使用 C++ 模板时出现错误 C2512 和错误 C2955

algorithm - "find the line that contains the maximum number of points in P"的哈希函数

c++ - 我认为与将值作为键相比,将 JsonValue 值分配给 JsonValues 可能会非常慢

c++ - 动态创建循环对象