示例代码是:
#include <iostream>
using std::cout;
using std::endl;
void bar(double *) {
cout << "call bar()" << endl;
}
using Bar = void(*)(double *);
template <Bar pfunction>
void foo() {
// when call "foo<bar>()", there is a warning:
// the address of ‘void bar(double*)’ will never be NULL [-Waddress]
if (nullptr != pfunction) {
pfunction(nullptr);
}
cout << "shit" << endl;
}
int main() {
foo<nullptr>(); // OK
foo<bar>(); // warning
return 0;
}
来自 gcc 手册:
-Waddress
Warn about suspicious uses of memory addresses. These include using the address of a function in a conditional expression, such as "void func(void); if (func)", and comparisons against the memory address of a string literal, such as "if (x == "abc")". Such uses typically indicate a programmer error: the address of a function always evaluates to true, so their use in a conditional usually indicate that the programmer forgot the parentheses in a function call.
最后一句误解了我的意思。在代码中,需要测试函数指针是否为nullptr
。我应该添加 -Wno-address
还是修改我的代码以消除警告?
2015.9.15更新。正如@SergeyA 所说,我使用模板特化,并且一切正常。
template <Bar pfunction>
void foo() {
pfunction(nullptr);
cout << "shit" << endl;
}
template <>
void foo<nullptr>() {
cout << "shit" << endl;
}
最佳答案
因为这是编译时代码,所以在此模板实例化中 Bar 永远不会为 null - 只有一个值。您不应将编译时编程与动态分支混合使用。为了实现您的目标(不是我理解您为什么希望您的 Bar 成为模板参数),您需要为 nullptr 专门化您的 foo。
关于c++ - g++ -Waddress 可能会误解我的意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32166386/