【发布时间】:2014-02-17 17:30:27
【问题描述】:
如何确保在编译时调用特定方法?
例如,假设我有一个具有 2 个方法的对象:
struct Foo
{
... func1(...);
... func2(...);
};
并且我想确保在调用 func2 之前调用 func1,即:
int main()
{
Foo f;
...
f.func1(...);
f.func2(...);
f.func2(...); // and so on
}
但如果我这样做,我想生成一个编译错误:
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
}
【问题讨论】:
-
您可以尝试使用
constexpr,但在这种情况下将不起作用。 (在任何情况下都不能保证真的有效)。 -
我猜这只能通过代码分析器来完成。编译器本身只能警告您未使用的函数 - AFAIK。
-
如果您需要这样做,您可能应该继续考虑更好的类设计。这是一个顺序耦合反模式:en.wikipedia.org/wiki/Sequential_coupling