如果某个类型未使用返回值,则编译失败 [英] Failing compilation if return value is unused for a certain type

查看:464
本文介绍了如果某个类型未使用返回值,则编译失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为某些函数调用而不是其他函数调用失败。我想失败的函数调用是那些在值为某种类型时不处理返回值的函数。在下面的示例中,不处理返回的函数是一个编译错误,但不处理返回任何其他应该成功的函数。

I would like to make compilation fail for some function call but not others. The function call that I want to fail are those that do not handle return values when the value is of a certain type. In the example below, not handling a function returning Error is a compilation error but not handling a function that returns anything else should succeed just fine.

注意:我们的运行环境(嵌入式)不允许我们使用下面的结构:RTTI,exception。

Note: our runtime environment (embedded) does not allow us to use the following constructs: RTTI, exceptions.

与Clang,我不想注释每个函数。

This code only needs to compiler with Clang, I would prefer not having to annotate each function.

我们更喜欢一个解决方案,在编译时失败,而不是在运行时。

We prefer a solution that fails at compile time instead of at runtime.

enum class Error {
  INVAL,
  NOERR,
};

// do something that can fail.
Error DoThing();
// may return different return codes, we never care (we can't change prototype)
int DoIgnoredThing();

int main() {
  DoThing(); // compilation failure here, unused "Error" result
  DoIgnoredThing(); // compilation succeeds, OK to ignore unused "int" result
  return 0;
}


推荐答案

我不知道一种使用直接C ++的方法,但是如果你使用g ++,你可以使用 warn_unused_result属性以及-Werror = unused-result命令行标志。请参阅warn_unused结果的文档以了解如何指定它(你必须在每个函数上指定它;不幸的是,我不相信你可以为类型指定它)。

I don't know of a way to do it with straight C++, but if you're using g++ you can use the warn_unused_result attribute along with the -Werror=unused-result command-line flag. See the documentation for warn_unused result for how to specify it (you'll have to specify it on every function unfortunately; I don't believe you can specify it for a type). Then the compiler flag will turn that warning into an error.

如果你不使用g ++,你的编译器可能有类似的功能。

If you're not using g++, your compiler may have similar functionality.

这篇关于如果某个类型未使用返回值,则编译失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆