c++ - 为什么不允许使用 0 作为 void* 的默认非类型模板参数

标签 c++ templates c++11 c++14 void

为什么下面的代码编译失败?尽管这样做是合法的 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 不允许出现在常量表达式中;也不可能在编译时将其转换为某些对象类型 TT*

关于c++ - 为什么不允许使用 0 作为 void* 的默认非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154762/

相关文章:

c++ - 连接正向和反向 vector

c++ - 如何在 C++ 中将内存块读取为 char

c++ - 如何编写模板函数,其参数类型需要继承某个类

c++ - 在clang 11上显式模板实例化期间的编译器段错误

c++ - get_time 未按预期运行

c++ - 如何在编译时查询一个类的所有基类?

c++ - 指向 std::array 成员的指针

java - 在java接口(interface)声明中使用模板参数

c++ - 如何确定 C++ 中实例化容器模板的容器模板类型

c++ - 如何初始化指向指针数组的指针?