c++ - (操作方法)获取编译器关于某个 c++ 年份的弃用/不推荐功能/构造的警告

标签 c++ c++17 compiler-warnings

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

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

也就是说,我想在 c++17 的“正统 c++17”子集中编码;-)

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

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

最佳答案

好吧,使用 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 将被弃用\"")'

C++ 有 [[deprecated]],但它弃用了变量,而不是 typedef,因此它没有正确的意图。它适用于更多的编译器,因此如果您的团队/您同意约定,您可以使用它,作为您同意不在代码中使用 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
      |             ^~~~~~~~

关于c++ - (操作方法)获取编译器关于某个 c++ 年份的弃用/不推荐功能/构造的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935680/

相关文章:

c++ - 如何使用 emplace 在 C++ 中添加 map ?

c++ - C++表达式模板的标准设计步骤,如何设计?

c++ - Wl,--stack,4194304 错误 Visual Studio/CMake

c++ - C++17是基于C17的吗?

c++ - 忽略 gcc/clang 的 "-Wmissing-braces"警告是否明智?

c++ - 为什么 g++ 在通过 const 引用将未初始化的值传递给函数时不报告警告?

c++ - 设置源和听者的位置无效

c++ - std::variant的参数归纳

C++ 元编程 : Generating a byte sequence based on type/value input?

clang 同义反复常量超出范围比较警告