g++ -Waddress 可能会误解我的意思

g++ -Waddress may misunderstand my meaning

示例代码为:

#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。