没有定义的结构模板的目的是什么

What is the purpose of a struct template without definition?

本文关键字:是什么 结构 定义      更新时间:2023-10-16

下面是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>不必完整即可编译此代码,因此它只是声明的,而不是定义的。使其完整只会为编译器增加额外的工作。