在编译时确保调用方法

Ama*_*eus 1 c++ c++11

如何在编译时确保调用特定方法?

例如,假设我有一个包含2个方法的对象:

struct Foo
{
   ... func1(...);
   ... func2(...);
};
Run Code Online (Sandbox Code Playgroud)

我想确保在调用func2之前调用func1,即:

int main()
{
   Foo f;
   ...
   f.func1(...);
   f.func2(...);
   f.func2(...); // and so on
}
Run Code Online (Sandbox Code Playgroud)

但是如果我这样做的话,我想生成一个编译错误:

int main()
{
   Foo f;
   ...
   f.func2(...);  // generate a compile error due the fact that func1 must be called first
   f.func1(...);
   f.func2(...); // and so on
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*rop 11

虽然好奇为什么要这样做,但一般要注意的是,必须向用户公开一个不能错误使用的界面.胆量私有化:

struct Foo
{
public:
    void callme()
    {
        func1();
        func2();
    }

private:
    ... func1(...);
    ... func2(...);


};

int main()
{
    Foo f;
    f.callme();
}
Run Code Online (Sandbox Code Playgroud)

如果需要强制执行一次对象初始化,请在构造函数中执行:

struct Foo
{
public:
    Foo()
    {
        func1();
    }

    func2(...);
private:
    ... func1(...);
};

int main()
{
    Foo f; // func1() called automagically
    f.func2();
}
Run Code Online (Sandbox Code Playgroud)

设计类接口时,你必须总是考虑最糟糕的事情:用户永远不会阅读文档,用户总是忘记打电话foo.initialize(),用户总是忘记释放内存和泄漏等.


Jar*_*Par 5

在编译时没有真正的方法来强制执行此操作.这是对象本身需要通过运行时检查来强制执行的操作