Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ g++-我可能会误解我的意思_C++_Templates_Function Pointers - Fatal编程技术网

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

C++ g++-我可能会误解我的意思,c++,templates,function-pointers,C++,Templates,Function Pointers,示例代码为: #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>()"

示例代码为:

#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;
}

因为这是编译时代码,所以在这个模板中,实例化条将永远不会为null——它只有一个值。您不应该将编译时编程与动态分支混合使用。为了实现您的目标(我并不理解您为什么希望条形图成为模板参数),您需要为nullptr专门化foo。

您可以使用
静态断言
,而不是
if
,将测试移到编译时。如果
nullptr
不是有效值,则将其作为函数引用?我将模板参数修改为
const Bar&pfunction
,但编译错误。@zenith
template <Bar pfunction>
void foo() {
    pfunction(nullptr);
    cout << "shit" << endl;
}

template <>
void foo<nullptr>() {
    cout << "shit" << endl;
}