没有定义的结构模板的目的是什么
What is the purpose of a struct template without definition?
下面是Boost.Python源代码的片段:
template <class T> struct null_ok; // how's it working?
template <class T>
inline null_ok<T>* allow_null(T* p)
{
return (null_ok<T>*)p;
}
有线有线没有前向声明结构null_ok
的定义,null_ok
与模板参数无关T
。
在Python wiki中,给出了一些提示:
句柄<> y(null_ok(x)) 允许 y 变为 NULL
句柄<> y(x),其中 x 不是null_ok的结果,永远不会导致 NULL y。如果 x 为 NULL 将引发异常
我无法弄清楚结构模板的声明(没有定义)null_ok
如何实现上述目的?
关键是将"此指针可以为 null"以及指针本身类型中的原始类型一起编码。
然后,可以重载接受指针的函数模板以识别null_ok<T>*
指针,而不会在空指针上出错(同时将其转换回T*
)。
你不需要 null_ok
的定义,因为您可以有指向不完整类型的指针,并且可以防止人们意外编写类似 null_ok<int> a;
的东西。
与您的代码片段下方handle.hpp
中的代码完全一致(我的评论):
// this is a borrowed handle which can be null,
// so increment refcount if p is not null
// (xincref just does nothing in this case)
template <class T>
inline T* manage_ptr(detail::borrowed<null_ok<T> >* p, int)
{
return python::xincref((T*)p);
}
// the same - as stated in the doc, null_ok and borrowed are commutative
template <class T>
inline T* manage_ptr(null_ok<detail::borrowed<T> >* p, int)
{
return python::xincref((T*)p);
}
// this is a borrowed handle which cannot be null, so make sure p is not null
// and increment refcount.
template <class T>
inline T* manage_ptr(detail::borrowed<T>* p, long)
{
return python::incref(expect_non_null((T*)p));
}
// p is not borrowed and can be null - do nothing.
template <class T>
inline T* manage_ptr(null_ok<T>* p, long)
{
return (T*)p;
}
// p is not borrowed and cannot be null - make sure it isn't null indeed.
template <class T>
inline T* manage_ptr(T* p, ...)
{
return expect_non_null(p);
}
null_ok<T>
不必完整即可编译此代码,因此它只是声明的,而不是定义的。使其完整只会为编译器增加额外的工作。
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- "perf_event_attr"结构的"read_format"属性的选项到底是什么?
- C++中deque数据结构的大O是什么?
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么
- 不同的类或结构初始化方法之间的性能差异是什么?
- 结构块指的是什么?
- C++ 类层次结构中的"对齐"是什么意思?
- 自定义数据结构的优点是什么?
- 将此私有删除器函数包装在结构中的目的是什么?
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- 这里的以下 OOP 结构是什么?
- 用于筛子的最佳数据结构是什么(即一些被划掉的数字列表)?
- 将一种数据类型的向量复制到同一数据类型的结构向量中的有效方法是什么
- 在结构中使用联合的目的是什么?
- c++ 17 中结构自动定义构造函数的规则是什么?
- 对于可重定位的多平台安装,理想的 cmake 安装目录结构是什么?
- 结构化绑定的用例是什么?
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 是什么让这种易失性打破了结构的指针算法?
- 这个嵌套结构声明是什么意思?