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