功能说明
如果我有这样的 fnc:
void fnc(const SomeType&){/**/}
当我列出此 fnc 的前提条件和后置条件时,我认为列出以下形式的前提条件:
SomeType 必须是正确的类型 相当愚蠢,不是吗?我之所以要求这个,是因为在我的大学,他们希望我们列出类似的内容,但如果参数的类型不正确,代码无论如何都不会编译,所以我认为这种形式的前提条件是错误的。但和往常一样,我错了。
If I have fnc like this:
void fnc(const SomeType&){/**/}
And when I list preconditions and postconditions for this fnc I think that listing precondition of form:
SomeType must be of a correct type is rather dumb, isn't it? I'm asking for this because at my uni they want us to list something like this but if the type of an arg won't be correct code won't compile anyway so I think it is wrong to have precondition of this form. But as usual, I my be wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要说出显而易见的事情。
正如您所说,如果类型不匹配,代码显然无法编译。
前置条件和后置条件将取决于函数试图执行的操作。
Don't state the obvious.
As you say, the code clearly won't compile if the types don't match up.
The pre- and post-conditions will depend on what the function is trying to do.
如果您的老师要求您添加此类注释,则可能不适用于简单的情况,因为此类注释只是简单的愚蠢且无论如何都会被编译器验证。
但在某些情况下,算法中定义的形式类型可能比 C++ 中使用的实现类型更具限制性。在这种情况下,这种评论可能会有一些用处。
另一个有用的案例是基于注释自动生成文档,但文档系统应该能够从函数原型中自行提取该信息。
If your teachers are asking you to add comments of this kind, it's probably not for the simple cases, when such comment are just plain dumb and verified by the compiler anyway.
But in some cases, the formal type defined in the algorithm may be more restrictive than the implementation type used in C++. In such cases that kind of comments may have some use.
Another usefull case is for autogenerated documentation based on comments, but the documentation system should be able to extract that information by itself from function prototype.
我会这样表述:
编译器是否可以检查并不重要。如果可以从函数的签名中设计出一些前提条件,这并不意味着这些东西不是前提条件。阅读前提条件后,用户应该能够编写可以正确编译和运行的程序。
I'd state it like this:
Whether compiler can check it doesn't matter. If some preconditions can be devised from signature of a function, that doesn't mean that these things aren't preconditions. Having read the preconditions, user should be capable to writing a program that would be correctly compiled and run.
做出这样的评论是愚蠢的——我同意。评论应该提供一些有用的信息。
前提条件列表应该告诉我们必须满足什么才能运行该函数。后置条件列表应该告诉函数退出时必须满足什么。您可以通过三种方式检查这些条件:
您还可以在函数注释中添加模板参数列表,如果不这样做则使编译失败符合要求。
Make comments like that is stupid - I agree. The comments should provide some useful information.
List of preconditions should tell what has to be satisfied in order to run the function. List of postconditions should tell what has to be satisfied at the function's exit. You can check those conditions in three ways :
You can also add a list of template arguments to the function comment, and make the compilation fails if they do not match the requirements.