(操作方法)在某个 c++ 年份获取关于 deprecated/unrecommended features/constructs 的编译器警告

(how-to) get compiler warning about deprecated/unrecommended features/constructs for a certain c++year

我正在寻找一个编译器开关(或 _SOME_MACRO),它将警告或禁止不再推荐(尽管仍然允许)用于 "selected" c++ 的功能或构造年。

例如。当使用 switch -std=c++17 编译 g++ 时,我想在使用 obsolete superseded "typedef" 构造时发出警告。

也就是说,我想在 c++17 的 "orthodox c++17" 子集中编码;-)

typedef int Sequence; // I would like a warning here

编辑:更清楚地表达我的愿望:我想在作者创建的 c++17 的 ideal/reformed 子集中编程,如果他们选择忽略任何和所有向后兼容性。我知道这不是严格正式和真实的事务声明,但我相信它足以说明我的观点。

正如您可能已经猜到的那样,由于 typedef 是编译器指令而不是函数或 class,因此无法像使用 [= 的函数或宏那样重新定义它12=] 然后重新定义.

#include <cstdio>
#undef printf

[[deprecated( “please don’t use printf!” )]]
int printf(const char *format, ...) {

你最好的选择是将像 clang-tidy 这样的 linter 绑定到你的构建系统中来预处理语法。毕竟,您想要向 程序员 而不是编译器发出警告指令。让编译器自己编译而不给它额外的工作是明智的。

此外,请记住 typedef 是完全有效的 C++,并且在 type-aliasing 之外也很有用,就像 union 是有效的一样,即使在 [=15] 中也有其作用=]可用。

编译器开发人员 在构造完全被标准委员会废弃时自己添加这些警告。 register 将是一个典型的例子。

好吧,使用 gcc 和一些宏滥用你可以这样做:

#define typedef _Pragma("GCC warning \"typedef is deprecated in my code base\"") typedef

typedef int Sequence; // I would like a warning here

将在gcc中生成:

<source>:3:13: warning: typedef is deprecated in my code base
    3 |     typedef int Sequence; // I would like a warning here
      |             ^~~~~~~~~~~~~~~~~~~~~~~

您可以将 _Pragma("GCC warning \"string\"") 更改为 _Pragma("message \"string\") 或真正更改为 _Pragma("GCC error \"string\"") 以获得编译错误。您可以将它作为参数添加到编译行 -D'typedef=_Pragma("GCC warning \"I consider typedef to be deprecated\"")'.

C++ 有 [[deprecated]],但它弃用了变量,而不是 typedef,因此它没有正确的意图。它适用于更多的编译器,因此如果您的 team/you 同意约定,您可以使用它,作为您同意不在代码中使用 typedef 的提示。

#define typedef [[deprecated]] typedef

typedef int Sequence; // I would like a warning here

int main() { 
    Sequence a;
}

将在 gcc 9.1 中输出:

<source>: In function 'int main()':
<source>:6:14: warning: 'Sequence' is deprecated [-Wdeprecated-declarations]
    6 |     Sequence a;
      |              ^
<source>:3:13: note: declared here
    3 | typedef int Sequence; // I would like a warning here
      |             ^~~~~~~~