如何在C ++模板函数中使用GCC诊断编译指示? [英] How to use GCC diagnostic pragma with C++ template functions?

查看:96
本文介绍了如何在C ++模板函数中使用GCC诊断编译指示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用g ++和 -Werror ,所以我现在必须禁用无法控制的第三方库的警告. http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html 的效果非常好,只需将第三方标头的包含内容与实用程序一起包装即可.不幸的是,在涉及模板的特定设置中,这不再对我有用.我创建了以下最小示例,说明这种方法无法按预期工作:

I would like to use g++ and -Werror, so I have now to disable warnings for 3rd-party libraries I have no control of. The solution provided by http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html works very well, allowing simply to wrap the includes of 3rd party headers with pragmas. Unfortunately, that did no longer work for me in a certain setup where templates are involved. I created the following minimal example of where this approach did not work as expected:

源文件main.cpp

Source file main.cpp

#pragma GCC diagnostic ignored "-Wunused-parameter"
#include "hdr.hpp"
#pragma GCC diagnostic error "-Wunused-parameter"
int main() {
    return mytemplatefunc(2) + mystandardfunc(3); // will print ONLY ONE warning
}

和标头hdr.hpp

and the header hdr.hpp

template<typename T>
int mytemplatefunc(T t) {
    return 42;
}
int mystandardfunc(int i) {
    return 53;
}

使用Makefile编译

compiled using Makefile

CPPFLAGS+=-Wunused-parameter -Werror
main: main.cpp

将产生以下编译器错误

g++  -Wunused-parameter -Werror   main.cpp   -o main
In file included from main.cpp:3:
hdr.hpp: In instantiation of ‘int mytemplatefunc(T) [with T = int]’:
main.cpp:29:   instantiated from here
hdr.hpp:2: error: unused parameter ‘t’
make: *** [main] Error 1
shell returned 2

请注意,直接在包含标头之后在main.cpp中进行显式实例化是行不通的,并且将对包装函数的调用包装在main.cpp中也不起作用.令人困惑的是,将#pragma GCC diagnostic ignored "-Wunused-parameter"放在主函数前面会使编译器静音,然后在文件的非常末端中添加#pragma GCC diagnostic error "-Wunused-parameter"会导致编译器再次产生错误.如何解决这个难题?

Note that explicit instantiation in main.cpp directly after including the header did not work, and wrapping the call to the template function in main.cpp did not work either. What was puzzling that putting #pragma GCC diagnostic ignored "-Wunused-parameter" in front of the main function silenced the compiler, whilst then adding #pragma GCC diagnostic error "-Wunused-parameter" at the very end of the file caused the compiler to produce the error again. How to solve this puzzle?

(请注意,关于此编译指示有很多线程,但是我找不到任何人 涉及到这样的设置)

(Note, there are dozens of threads about this pragma, but I could not find anyone that involved such a setup)

推荐答案

问题是模板的实例化是在您使用模板时进行编译的,而不是在编译器在头文件中对其进行解析时进行编译的,因此它将不会发出警告,直到它用int替换T并将其解析为在编译指示沉默范围之外的常规函数​​.

The issue is that the instantiation of the template is compiled when you use it, not when it is parsed by the compiler in the header file so it will not issue the warning until it replaces T by int and parses it as a regular function outside the context of the pragma silencing.

这篇关于如何在C ++模板函数中使用GCC诊断编译指示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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