Wil*_*mKF 11 c++ templates language-lawyer member-variables
目前,我使用以下函数模板来抑制未使用的变量警告:
template<typename T>
void
unused(T const &) {
/* Do nothing. */
}
Run Code Online (Sandbox Code Playgroud)
但是,当从Linux移植到cygwin时,我现在在g ++ 3.4.4上遇到编译器错误(在linux上我是3.4.6,所以这可能是一个bug修复?):
Write.cpp: In member function `void* Write::initReadWrite()':
Write.cpp:516: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
../../src/common/Assert.h:27: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
make[1]: *** [ARCH.cygwin/release/Write.o] Error 1
Run Code Online (Sandbox Code Playgroud)
未使用的参数是一个声明为的成员变量:
volatile bool readWriteActivated;
Run Code Online (Sandbox Code Playgroud)
这是编译器错误还是我的代码中的错误?
这是最小的测试用例:
template<typename T>
void unused(T const &) { }
int main() {
volatile bool x = false;
unused(!x); // type of "!x" is bool
}
Run Code Online (Sandbox Code Playgroud)
haa*_*vee 28
指示您实际上不使用参数的实际方法是不给它命名:
int f(int a, float) {
return a*2;
}
Run Code Online (Sandbox Code Playgroud)
将打开所有警告的所有地方编译,而不会警告未使用的浮动.即使参数确实在原型中有一个名称(例如int f(int a, float f);),它仍然不会抱怨.
我不是100%确定这是可移植的,但这是我通常用来抑制有关未使用变量的警告的习惯用法.这里的背景是一个信号处理程序,只用来捕捉SIGINT和SIGTERM,所以如果函数永远叫我知道它的时候,程序退出.
volatile bool app_killed = false;
int signal_handler(int signum)
{
(void)signum; // this suppresses the warnings
app_killed = true;
}
Run Code Online (Sandbox Code Playgroud)
我倾向于不喜欢混乱参数列表__attribute__((unused)),因为无需借助于Visual C++的宏就可以使用转换为无效的技巧.