为什么下面的代码编译失败?尽管这样做是合法的 void* ptr = 0;
template <void* ptr = 0>
void func();
int main() {
func();
return 0;
}
我问是因为我发现一个非常可信的来源做了类似的事情,但在我的机器上编译失败
注意 应该将编译器错误与我的问题一起发布,所以在这里
so_test.cpp:1:23: error: null non-type template argument must be cast to template parameter type 'void *'
template <void* ptr = 0>
^
static_cast<void *>( )
so_test.cpp:1:17: note: template parameter is declared here
template <void* ptr = 0>
^
so_test.cpp:5:5: error: no matching function for call to 'func'
func();
^~~~
so_test.cpp:2:6: note: candidate template ignored: substitution failure [with ptr = nullptr]: null non-type template argument must be cast to template parameter type 'void *'
void func();
^
最佳答案
void*
类型的模板参数是不允许的。请参阅标准中的 [temp.param]/4,也在 http://en.cppreference.com/w/cpp/language/template_parameters#Non-type_template_parameter 中进行了总结。
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
- integral or enumeration type,
- pointer to object or pointer to function,
- lvalue reference to object or lvalue reference to function,
- pointer to member,
std::nullptr_t
.
由于 void
不是对象或函数类型,因此 void*
不属于允许的类型。
附录:在编译时已知的 void*
值不会很有用。不可能在编译时检查它的值,因为 reinterpret_cast
不允许出现在常量表达式中;也不可能在编译时将其转换为某些对象类型 T
的 T*
。
关于c++ - 为什么不允许使用 0 作为 void* 的默认非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154762/