1.0 新版功能.

最初,Sphinx 是为一个单一的项目设想的,即 Python 语言的文档。不久之后,它作为一个文档工具提供给所有人,但 Python 模块的文档仍然深深地内置于其中–最基本的指令,如 function,是为 Python 对象设计的。由于 Sphinx 已经变得有些流行,人们对将其用于许多不同的目的产生了兴趣:C/C++ 项目,JavaScript,甚至是 reStructuredText 标记(比如这个文档)。

虽然这一直是可能的,但现在通过为每一个这样的目的提供一个 ,可以更容易地支持使用不同编程语言的项目的文档,甚至是主要的 Sphinx 发行版不支持的项目。

域是一个标记的集合(reStructuredText 指令角色),用来描述和链接属于一起的 对象,例如,编程语言的元素。域中的指令和角色名称有类似 domain:name 的名称,例如 py:function。域也可以提供自定义索引(如 Python 模块索引)。

拥有域意味着当一组文档想要引用例如 C++ 和 Python 类时,不会出现命名问题。这也意味着支持整个新语言的文档的扩展更容易编写。

本节描述了包括在 Sphinx 中的域所提供的东西。域的 API 也被记录在 Domain API 部分。

基础标记

大多数域提供了一些 object description directives,用于描述模块提供的特定对象。每个指令都需要一个或多个签名,以提供关于被描述的内容的基本信息,而内容应该是描述。一个域通常会保留一个所有实体的内部索引以帮助交叉引用。通常,它也会在显示的一般索引中添加条目。如果你想抑制在显示的索引中添加条目,你可以给指令的选项标志 :noindexentry:。如果你想排版一个对象的描述,甚至不使其可用于交叉引用,你可以给指令选项标志 :noindex: (这意味着 :noindexentry:)。不过,请注意,不是每个域的每个指令都可能支持这些选项。

3.2 新版功能: Python、C、C++ 和 Javascript 域的指令选项 noindexentry

一个使用 Python 域指令的例子

.. py:function:: spam(eggs)
                 ham(eggs)

   Spam or ham the foo.

这描述了两个 Python 函数 spamham。(注意,当签名变得太长时,如果你在下一行继续的行中添加反斜杠,就可以将其断开。例如

.. py:function:: filterwarnings(action, message='', category=Warning, \
                                module='', lineno=0, append=False)
   :noindex:

(这个例子也显示了如何使用 :noindex: 旗标)。

域还提供了链接到这些对象描述的角色。例如,要链接到上面例子中描述的一个函数,你可以

The function :py:func:`spam` does a similar thing.

正如你所看到的,指令和角色名称都包含域名和指令名称。

默认域

对于只描述一个域的对象的文档,作者不必在指定了默认值后,在每个指令、角色等处再次说明其名称。这可以通过配置值 primary_domain 或者通过这个指令来实现:

.. default-domain:: name

选择一个新的默认域。虽然 primary_domain 选择了一个全局默认,但这只在同一文件内有影响。

如果没有选择其他默认,Python 域(命名为 py)是默认的,主要是为了与为旧版本的 Sphinx 编写的文档兼容。

属于默认域的指令和角色可以不给出域名而被提及,即

.. function:: pyfunc()

   Describes a Python function.

Reference to :func:`pyfunc`.

交叉引用的语法

对于由域提供的交叉引用角色,存在与一般交叉引用相同的设施。参见 交叉引用语法

简而言之:

  • 你可以提供一个明确的标题和参考目标::role:`title <target>` 将引用 target,但链接文本将是 title

  • 如果你在内容前面加上 !,将不会创建任何参考/超级链接。

  • 如果你在内容前加上 ~,链接文本将只作为目标的最后一个组件。例如,:py:meth:`~Queue.Queue.get` 将引用 Queue.Queue.get 但只显示 get 作为链接文本。

Python 域

Python 域(名称为 py)为模块声明提供了以下指令:

.. py:module:: name

这条指令标志着一个模块(或包的子模块,在这种情况下,名称应该是完全限定的,包括包的名称)描述的开始。它不创建内容(比如 py:class)。

这条指令也会在全局模块索引中引起一个条目。

选项

:platform: platforms (comma separated list)

指出该模块可用的平台(如果它在所有平台上都可用,该选项应省略)。键是简短的标识符;正在使用的例子包括 “IRIX”、”Mac”、”Windows” 和 “Unix”。在适用的情况下,使用已经使用过的键是很重要的。

:synopsis: purpose (text)

由一句话组成,描述该模块的目的 —— 目前只在全局模块索引中使用。

:deprecated: (no argument)

将一个模块标记为弃用;届时它将在不同的地方被指定为弃用。

.. py:currentmodule:: name

这个指令告诉 Sphinx,从这里记录的类、函数等都在给定的模块中(就像 py:module),但它不会为 py:mod 创建索引条目、全局模块索引中的条目或一个链接目标。这在一个模块的文档分布在多个文件或部分的情况下很有帮助 —— 一个地方有 py:module 指令,其他地方只有 py:currentmodule

为模块和类的内容提供了以下指令:

.. py:function:: name(parameters)

Describes a module-level function. The signature should include the parameters as given in the Python function definition, see Python Signatures. For example:

.. py:function:: Timer.repeat(repeat=3, number=1000000)

For methods you should use py:method.

The description normally includes information about the parameters required and how they are used (especially whether mutable objects passed as parameters are modified), side effects, and possible exceptions.

This information can (in any py directive) optionally be given in a structured form, see Info field lists.

选项

:async: (no value)

Indicate the function is an async function.

2.1 新版功能.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

4.0 新版功能.

.. py:data:: name

Describes global data in a module, including both variables and values used as “defined constants.” Class and object attributes are not documented using this environment.

选项

:type: type of the variable (text)

2.4 新版功能.

:value: initial value of the variable (text)

2.4 新版功能.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

4.0 新版功能.

.. py:exception:: name

Describes an exception class. The signature can, but need not include parentheses with constructor arguments.

选项

:final: (no value)

Indicate the class is a final class.

3.1 新版功能.

.. py:class:: name
.. py:class:: name(parameters)

Describes a class. The signature can optionally include parentheses with parameters which will be shown as the constructor arguments. See also Python Signatures.

Methods and attributes belonging to the class should be placed in this directive’s body. If they are placed outside, the supplied name should contain the class name so that cross-references still work. Example:

.. py:class:: Foo

   .. py:method:: quux()

-- or --

.. py:class:: Bar

.. py:method:: Bar.quux()

The first way is the preferred one.

选项

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

4.0 新版功能.

:final: (no value)

Indicate the class is a final class.

3.1 新版功能.

.. py:attribute:: name

Describes an object data attribute. The description should include information about the type of the data to be expected and whether it may be changed directly.

选项

:type: type of the attribute (text)

2.4 新版功能.

:value: initial value of the attribute (text)

2.4 新版功能.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

4.0 新版功能.

.. py:property:: name

Describes an object property.

4.0 新版功能.

选项

:abstractmethod: (no value)

Indicate the property is abstract.

:classmethod: (no value)

Indicate the property is a classmethod.

:type: type of the property (text)
.. py:method:: name(parameters)

Describes an object method. The parameters should not include the self parameter. The description should include similar information to that described for function. See also Python Signatures and Info field lists.

选项

:abstractmethod: (no value)

Indicate the method is an abstract method.

2.1 新版功能.

:async: (no value)

Indicate the method is an async method.

2.1 新版功能.

:canonical: (full qualified name including module name)

Describe the location where the object is defined if the object is imported from other modules

4.0 新版功能.

:classmethod: (no value)

Indicate the method is a class method.

2.1 新版功能.

:final: (no value)

Indicate the class is a final method.

3.1 新版功能.

:property: (no value)

Indicate the method is a property.

2.1 新版功能.

4.0 版后已移除: Use py:property instead.

:staticmethod: (no value)

Indicate the method is a static method.

2.1 新版功能.

.. py:staticmethod:: name(parameters)

Like py:method, but indicates that the method is a static method.

0.4 新版功能.

.. py:classmethod:: name(parameters)

Like py:method, but indicates that the method is a class method.

0.6 新版功能.

.. py:decorator:: name
.. py:decorator:: name(parameters)

Describes a decorator function. The signature should represent the usage as a decorator. For example, given the functions

def removename(func):
    func.__name__ = ''
    return func

def setnewname(name):
    def decorator(func):
        func.__name__ = name
        return func
    return decorator

the descriptions should look like this:

.. py:decorator:: removename

   Remove name of the decorated function.

.. py:decorator:: setnewname(name)

   Set name of the decorated function to *name*.

(as opposed to .. py:decorator:: removename(func).)

There is no py:deco role to link to a decorator that is marked up with this directive; rather, use the py:func role.

.. py:decoratormethod:: name
.. py:decoratormethod:: name(signature)

Same as py:decorator, but for decorators that are methods.

Refer to a decorator method using the py:meth role.

Python Signatures

Signatures of functions, methods and class constructors can be given like they would be written in Python.

Default values for optional arguments can be given (but if they contain commas, they will confuse the signature parser). Python 3-style argument annotations can also be given as well as return type annotations:

.. py:function:: compile(source : string, filename, symbol='file') -> ast object

For functions with optional parameters that don’t have default values (typically functions implemented in C extension modules without keyword argument support), you can use brackets to specify the optional parts:

compile(source[, filename[, symbol]])

It is customary to put the opening bracket before the comma.

Info field lists

0.4 新版功能.

在 3.0 版更改: meta fields are added.

Inside Python object description directives, reST field lists with these fields are recognized and formatted nicely:

  • param, parameter, arg, argument, key, keyword: Description of a parameter.

  • type: Type of a parameter. Creates a link if possible.

  • raises, raise, except, exception: That (and when) a specific exception is raised.

  • var, ivar, cvar: Description of a variable.

  • vartype: Type of a variable. Creates a link if possible.

  • returnsreturn:描述返回值。

  • rtype: Return type. Creates a link if possible.

  • meta: Add metadata to description of the python object. The metadata will not be shown on output document. For example, :meta private: indicates the python object is private member. It is used in sphinx.ext.autodoc for filtering members.

备注

In current release, all var, ivar and cvar are represented as “Variable”. There is no difference at all.

The field names must consist of one of these keywords and an argument (except for returns and rtype, which do not need an argument). This is best explained by an example:

.. py:function:: send_message(sender, recipient, message_body, [priority=1])

   Send a message to a recipient

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring

This will render like this:

send_message(sender, recipient, message_body[, priority=1])

Send a message to a recipient

参数
  • sender (str) – The person sending the message

  • recipient (str) – The recipient of the message

  • message_body (str) – The body of the message

  • priority (integer or None) – The priority of the message, can be a number 1-5

返回

the message id

返回类型

int

引发
  • ValueError – if the message_body exceeds 160 characters

  • TypeError – if the message_body is not a basestring

It is also possible to combine parameter type and description, if the type is a single word, like this:

:param int priority: The priority of the message, can be a number 1-5

1.5 新版功能.

Container types such as lists and dictionaries can be linked automatically using the following syntax:

:type priorities: list(int)
:type priorities: list[int]
:type mapping: dict(str, int)
:type mapping: dict[str, int]
:type point: tuple(float, float)
:type point: tuple[float, float]

Multiple types in a type field will be linked automatically if separated by the word “or”:

:type an_arg: int or None
:vartype a_var: str or int
:rtype: float or str

Cross-referencing Python objects

The following roles refer to objects in modules and are possibly hyperlinked if a matching identifier is found:

:py:mod:

Reference a module; a dotted name may be used. This should also be used for package names.

:py:func:

Reference a Python function; dotted names may be used. The role text needs not include trailing parentheses to enhance readability; they will be added automatically by Sphinx if the add_function_parentheses config value is True (the default).

:py:data:

Reference a module-level variable.

:py:const:

Reference a “defined” constant. This may be a Python variable that is not intended to be changed.

:py:class:

Reference a class; a dotted name may be used.

:py:meth:

Reference a method of an object. The role text can include the type name and the method name; if it occurs within the description of a type, the type name can be omitted. A dotted name may be used.

:py:attr:

Reference a data attribute of an object.

备注

The role is also able to refer to property.

:py:exc:

Reference an exception. A dotted name may be used.

:py:obj:

Reference an object of unspecified type. Useful e.g. as the default_role.

0.4 新版功能.

The name enclosed in this markup can include a module name and/or a class name. For example, :py:func:`filter` could refer to a function named filter in the current module, or the built-in function of that name. In contrast, :py:func:`foo.filter` clearly refers to the filter function in the foo module.

Normally, names in these roles are searched first without any further qualification, then with the current module name prepended, then with the current module and class name (if any) prepended. If you prefix the name with a dot, this order is reversed. For example, in the documentation of Python’s codecs module, :py:func:`open` always refers to the built-in function, while :py:func:`.open` refers to codecs.open().

A similar heuristic is used to determine whether the name is an attribute of the currently documented class.

Also, if the name is prefixed with a dot, and no exact match is found, the target is taken as a suffix and all object names with that suffix are searched. For example, :py:meth:`.TarFile.close` references the tarfile.TarFile.close() function, even if the current module is not tarfile. Since this can get ambiguous, if there is more than one possible match, you will get a warning from Sphinx.

Note that you can combine the ~ and . prefixes: :py:meth:`~.TarFile.close` will reference the tarfile.TarFile.close() method, but the visible link caption will only be close().

C 域

C 域(名称为 c)适用于 C API 的文档。

.. c:member:: declaration
.. c:var:: declaration

描述了一个 C 结构的成员或变量。签名示例

.. c:member:: PyObject *PyTypeObject.tp_bases

这两个指令之间的区别只是表面上的。

.. c:function:: function prototype

描述了一个 C 语言函数。签名应该按照 C 语言的方式给出,例如

.. c:function:: PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

请注意,你不必在签名中反斜线标出星号,因为它不会被 reST 内联程序解析。

在一个函数的描述中,你可以使用以下信息字段(也可参见 Info field lists)。

  • paramparameterargargument 描述一个参数。

  • type:参数的类型,就像传递给 c:expr 角色那样写。

  • returnsreturn:描述返回值。

  • rtype:返回类型,就像传递给 c:expr 角色那样写。

  • retvalretvals:替代 returns,用于描述函数的结果。

4.3 新版功能: retval 字段类型。

例如

.. c:function:: PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

   :param type: description of the first parameter.
   :param nitems: description of the second parameter.
   :returns: a result.
   :retval NULL: under some conditions.
   :retval NULL: under some other conditions as well.

渲染为

PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
参数
  • type – description of the first parameter.

  • nitems – description of the second parameter.

返回

a result.

Return values
  • NULL – under some conditions.

  • NULL – under some other conditions as well.

.. c:macro:: name
.. c:macro:: name(arg list)

描述一个 C 语言的宏,即一个 C 语言的 #define,没有替换文本。

在宏的描述中,你可以使用与 c:function 指令相同的信息域。

3.0 新版功能: 函数风格的变体。

.. c:struct:: name

描述 C 结构。

3.0 新版功能.

.. c:union:: name

描述 C 联合体。

3.0 新版功能.

.. c:enum:: name

描述 C 枚举。

3.0 新版功能.

.. c:enumerator:: name

描述了C 的枚举器。

3.0 新版功能.

.. c:type:: typedef-like declaration
.. c:type:: name

描述一个 C 类型,可以是一个类型定义,也可以是一个未指定的类型的别名。

Cross-referencing C constructs

The following roles create cross-references to C-language constructs if they are defined in the documentation:

:c:member:
:c:data:
:c:var:
:c:func:
:c:macro:
:c:struct:
:c:union:
:c:enum:
:c:enumerator:
:c:type:

Reference a C declaration, as defined above. Note that c:member, c:data, and c:var are equivalent.

3.0 新版功能: The var, struct, union, enum, and enumerator roles.

Anonymous Entities

C supports anonymous structs, enums, and unions. For the sake of documentation they must be given some name that starts with @, e.g., @42 or @data. These names can also be used in cross-references, though nested symbols will be found even when omitted. The @... name will always be rendered as [anonymous] (possibly as a link).

Example:

.. c:struct:: Data

   .. c:union:: @data

      .. c:var:: int a

      .. c:var:: double b

Explicit ref: :c:var:`Data.@data.a`. Short-hand ref: :c:var:`Data.a`.

This will be rendered as:

struct Data
union [anonymous]
int a
double b

Explicit ref: Data.[anonymous].a. Short-hand ref: Data.a.

3.0 新版功能.

Aliasing Declarations

Sometimes it may be helpful list declarations elsewhere than their main documentation, e.g., when creating a synopsis of an interface. The following directive can be used for this purpose.

.. c:alias:: name

Insert one or more alias declarations. Each entity can be specified as they can in the c:any role.

例如

.. c:var:: int data
.. c:function:: int f(double k)

.. c:alias:: data
             f

becomes

int data
int f(double k)
int data
int f(double k)

3.2 新版功能.

Options

:maxdepth: int

Insert nested declarations as well, up to the total depth given. Use 0 for infinite depth and 1 for just the mentioned declaration. Defaults to 1.

3.3 新版功能.

:noroot:

Skip the mentioned declarations and only render nested declarations. Requires maxdepth either 0 or at least 2.

3.5 新版功能.

Inline Expressions and Types

:c:expr:
:c:texpr:

Insert a C expression or type either as inline code (cpp:expr) or inline text (cpp:texpr). For example:

.. c:var:: int a = 42

.. c:function:: int f(int i)

An expression: :c:expr:`a * f(a)` (or as text: :c:texpr:`a * f(a)`).

A type: :c:expr:`const Data*`
(or as text :c:texpr:`const Data*`).

will be rendered as follows:

int a = 42
int f(int i)

An expression: a * f(a) (or as text: a * f(a)).

A type: const Data* (or as text const Data*).

3.0 新版功能.

Namespacing

3.1 新版功能.

The C language it self does not support namespacing, but it can sometimes be useful to emulate it in documentation, e.g., to show alternate declarations. The feature may also be used to document members of structs/unions/enums separate from their parent declaration.

The current scope can be changed using three namespace directives. They manage a stack declarations where c:namespace resets the stack and changes a given scope.

The c:namespace-push directive changes the scope to a given inner scope of the current one.

The c:namespace-pop directive undoes the most recent c:namespace-push directive.

.. c:namespace:: scope specification

Changes the current scope for the subsequent objects to the given scope, and resets the namespace directive stack. Note that nested scopes can be specified by separating with a dot, e.g.:

.. c:namespace:: Namespace1.Namespace2.SomeStruct.AnInnerStruct

All subsequent objects will be defined as if their name were declared with the scope prepended. The subsequent cross-references will be searched for starting in the current scope.

Using NULL or 0 as the scope will change to global scope.

.. c:namespace-push:: scope specification

Change the scope relatively to the current scope. For example, after:

.. c:namespace:: A.B

.. c:namespace-push:: C.D

the current scope will be A.B.C.D.

.. c:namespace-pop::

Undo the previous c:namespace-push directive (not just pop a scope). For example, after:

.. c:namespace:: A.B

.. c:namespace-push:: C.D

.. c:namespace-pop::

the current scope will be A.B (not A.B.C).

If no previous c:namespace-push directive has been used, but only a c:namespace directive, then the current scope will be reset to global scope. That is, .. c:namespace:: A.B is equivalent to:

.. c:namespace:: NULL

.. c:namespace-push:: A.B

Configuration Variables

See Options for the C domain.

C++ 域

C++ 域(名称为 cpp)支持记录 C++ 项目。

声明实体的指令

以下指令是可用的。所有的声明都可以以可见性声明开始(publicprivateprotected)。

.. cpp:class:: class specifier
.. cpp:struct:: class specifier

描述一个类/结构,可能带有继承性的说明,例如

.. cpp:class:: MyClass : public MyBase, MyOtherBase

cpp:classcpp:struct 之间的区别只是表面上的:输出中呈现的前缀,以及索引中显示的指定符。

The class can be directly declared inside a nested scope, e.g.,:

.. cpp:class:: OuterScope::MyClass : public MyBase, MyOtherBase

A class template can be declared:

.. cpp:class:: template<typename T, std::size_t N> std::array

or with a line break:

.. cpp:class:: template<typename T, std::size_t N> \
               std::array

Full and partial template specialisations can be declared:

.. cpp:class:: template<> \
               std::array<bool, 256>

.. cpp:class:: template<typename T> \
               std::array<T, 42>

2.0 新版功能: The cpp:struct directive.

.. cpp:function:: (member) function prototype

描述一个函数或成员函数,如

.. cpp:function:: bool myMethod(int arg1, std::string arg2)

   A function with parameters and types.

.. cpp:function:: bool myMethod(int, double)

   A function with unnamed parameters.

.. cpp:function:: const T &MyClass::operator[](std::size_t i) const

   An overload for the indexing operator.

.. cpp:function:: operator bool() const

   A casting operator.

.. cpp:function:: constexpr void foo(std::string &bar[2]) noexcept

   A constexpr function.

.. cpp:function:: MyClass::MyClass(const MyClass&) = default

   A copy constructor with default implementation.

函数模板也可以被描述为

.. cpp:function:: template<typename U> \
                  void print(U &&u)

和函数模板的专有

.. cpp:function:: template<> \
                  void print(int i)
.. cpp:member:: (member) variable declaration
.. cpp:var:: (member) variable declaration

描述一个变量或成员变量,例如

.. cpp:member:: std::string MyClass::myMember

.. cpp:var:: std::string MyClass::myOtherMember[N][M]

.. cpp:member:: int a = 42

变量模板也可以被描述为

.. cpp:member:: template<class T> \
                constexpr T pi = T(3.1415926535897932385)
.. cpp:type:: typedef declaration
.. cpp:type:: name
.. cpp:type:: type alias declaration

Describe a type as in a typedef declaration, a type alias declaration, or simply the name of a type with unspecified type, e.g.,:

.. cpp:type:: std::vector<int> MyList

   A typedef-like declaration of a type.

.. cpp:type:: MyContainer::const_iterator

   Declaration of a type alias with unspecified type.

.. cpp:type:: MyType = std::unordered_map<int, std::string>

   Declaration of a type alias.

A type alias can also be templated:

.. cpp:type:: template<typename T> \
              MyContainer = std::vector<T>

The example are rendered as follows.

typedef std::vector<int> MyList

A typedef-like declaration of a type.

type MyContainer::const_iterator

Declaration of a type alias with unspecified type.

using MyType = std::unordered_map<int, std::string>

Declaration of a type alias.

template<typename T>
using MyContainer = std::vector<T>
.. cpp:enum:: unscoped enum declaration
.. cpp:enum-struct:: scoped enum declaration
.. cpp:enum-class:: scoped enum declaration

Describe a (scoped) enum, possibly with the underlying type specified. Any enumerators declared inside an unscoped enum will be declared both in the enum scope and in the parent scope. Examples:

.. cpp:enum:: MyEnum

   An unscoped enum.

.. cpp:enum:: MySpecificEnum : long

   An unscoped enum with specified underlying type.

.. cpp:enum-class:: MyScopedEnum

   A scoped enum.

.. cpp:enum-struct:: protected MyScopedVisibilityEnum : std::underlying_type<MySpecificEnum>::type

   A scoped enum with non-default visibility, and with a specified
   underlying type.
.. cpp:enumerator:: name
.. cpp:enumerator:: name = constant

Describe an enumerator, optionally with its value defined, e.g.,:

.. cpp:enumerator:: MyEnum::myEnumerator

.. cpp:enumerator:: MyEnum::myOtherEnumerator = 42
.. cpp:union:: name

Describe a union.

1.8 新版功能.

.. cpp:concept:: template-parameter-list name

警告

The support for concepts is experimental. It is based on the current draft standard and the Concepts Technical Specification. The features may change as they evolve.

Describe a concept. It must have exactly 1 template parameter list. The name may be a nested name. Example:

.. cpp:concept:: template<typename It> std::Iterator

   Proxy to an element of a notional sequence that can be compared,
   indirected, or incremented.

   **Notation**

   .. cpp:var:: It r

      An lvalue.

   **Valid Expressions**

   - :cpp:expr:`*r`, when :cpp:expr:`r` is dereferenceable.
   - :cpp:expr:`++r`, with return type :cpp:expr:`It&`, when
     :cpp:expr:`r` is incrementable.

This will render as follows:

template<typename It>
concept std::Iterator

Proxy to an element of a notional sequence that can be compared, indirected, or incremented.

Notation

It r

An lvalue.

Valid Expressions

  • *r, when r is dereferenceable.

  • ++r, with return type It&, when r is incrementable.

1.5 新版功能.

Options

Some directives support options:

  • :noindexentry:, see 基础标记.

  • :tparam-line-spec:, for templated declarations. If specified, each template parameter will be rendered on a separate line.

    1.6 新版功能.

Anonymous Entities

C++ supports anonymous namespaces, classes, enums, and unions. For the sake of documentation they must be given some name that starts with @, e.g., @42 or @data. These names can also be used in cross-references and (type) expressions, though nested symbols will be found even when omitted. The @... name will always be rendered as [anonymous] (possibly as a link).

Example:

.. cpp:class:: Data

   .. cpp:union:: @data

      .. cpp:var:: int a

      .. cpp:var:: double b

Explicit ref: :cpp:var:`Data::@data::a`. Short-hand ref: :cpp:var:`Data::a`.

This will be rendered as:

class Data
union [anonymous]
int a
double b

Explicit ref: Data::[anonymous]::a. Short-hand ref: Data::a.

1.8 新版功能.

Aliasing Declarations

Sometimes it may be helpful list declarations elsewhere than their main documentation, e.g., when creating a synopsis of a class interface. The following directive can be used for this purpose.

.. cpp:alias:: name or function signature

Insert one or more alias declarations. Each entity can be specified as they can in the cpp:any role. If the name of a function is given (as opposed to the complete signature), then all overloads of the function will be listed.

例如

.. cpp:alias:: Data::a
               overload_example::C::f

becomes

int a
void f(double d) const
void f(double d)
void f(int i)
void f()

whereas:

.. cpp:alias:: void overload_example::C::f(double d) const
               void overload_example::C::f(double d)

becomes

void f(double d) const
void f(double d)

2.0 新版功能.

Options

:maxdepth: int

Insert nested declarations as well, up to the total depth given. Use 0 for infinite depth and 1 for just the mentioned declaration. Defaults to 1.

3.5 新版功能.

:noroot:

Skip the mentioned declarations and only render nested declarations. Requires maxdepth either 0 or at least 2.

3.5 新版功能.

Constrained Templates

警告

The support for concepts is experimental. It is based on the current draft standard and the Concepts Technical Specification. The features may change as they evolve.

备注

Sphinx does not currently support requires clauses.

Placeholders

Declarations may use the name of a concept to introduce constrained template parameters, or the keyword auto to introduce unconstrained template parameters:

.. cpp:function:: void f(auto &&arg)

   A function template with a single unconstrained template parameter.

.. cpp:function:: void f(std::Iterator it)

   A function template with a single template parameter, constrained by the
   Iterator concept.

Template Introductions

Simple constrained function or class templates can be declared with a template introduction instead of a template parameter list:

.. cpp:function:: std::Iterator{It} void advance(It &it)

    A function template with a template parameter constrained to be an
    Iterator.

.. cpp:class:: std::LessThanComparable{T} MySortedContainer

    A class template with a template parameter constrained to be
    LessThanComparable.

They are rendered as follows.

std::Iterator{It}
void advance(It &it)

A function template with a template parameter constrained to be an Iterator.

std::LessThanComparable{T}
class MySortedContainer

A class template with a template parameter constrained to be LessThanComparable.

Note however that no checking is performed with respect to parameter compatibility. E.g., Iterator{A, B, C} will be accepted as an introduction even though it would not be valid C++.

Inline Expressions and Types

:cpp:expr:
:cpp:texpr:

Insert a C++ expression or type either as inline code (cpp:expr) or inline text (cpp:texpr). For example:

.. cpp:var:: int a = 42

.. cpp:function:: int f(int i)

An expression: :cpp:expr:`a * f(a)` (or as text: :cpp:texpr:`a * f(a)`).

A type: :cpp:expr:`const MySortedContainer<int>&`
(or as text :cpp:texpr:`const MySortedContainer<int>&`).

will be rendered as follows:

int a = 42
int f(int i)

An expression: a * f(a) (or as text: a * f(a)).

A type: const MySortedContainer<int>& (or as text const MySortedContainer<int>&).

1.7 新版功能: The cpp:expr role.

1.8 新版功能: The cpp:texpr role.

Namespacing

Declarations in the C++ domain are as default placed in global scope. The current scope can be changed using three namespace directives. They manage a stack declarations where cpp:namespace resets the stack and changes a given scope.

The cpp:namespace-push directive changes the scope to a given inner scope of the current one.

The cpp:namespace-pop directive undoes the most recent cpp:namespace-push directive.

.. cpp:namespace:: scope specification

Changes the current scope for the subsequent objects to the given scope, and resets the namespace directive stack. Note that the namespace does not need to correspond to C++ namespaces, but can end in names of classes, e.g.,:

.. cpp:namespace:: Namespace1::Namespace2::SomeClass::AnInnerClass

All subsequent objects will be defined as if their name were declared with the scope prepended. The subsequent cross-references will be searched for starting in the current scope.

Using NULL, 0, or nullptr as the scope will change to global scope.

A namespace declaration can also be templated, e.g.,:

.. cpp:class:: template<typename T> \
               std::vector

.. cpp:namespace:: template<typename T> std::vector

.. cpp:function:: std::size_t size() const

declares size as a member function of the class template std::vector. Equivalently this could have been declared using:

.. cpp:class:: template<typename T> \
               std::vector

   .. cpp:function:: std::size_t size() const

or:

.. cpp:class:: template<typename T> \
               std::vector
.. cpp:namespace-push:: scope specification

Change the scope relatively to the current scope. For example, after:

.. cpp:namespace:: A::B

.. cpp:namespace-push:: C::D

the current scope will be A::B::C::D.

1.4 新版功能.

.. cpp:namespace-pop::

Undo the previous cpp:namespace-push directive (not just pop a scope). For example, after:

.. cpp:namespace:: A::B

.. cpp:namespace-push:: C::D

.. cpp:namespace-pop::

the current scope will be A::B (not A::B::C).

If no previous cpp:namespace-push directive has been used, but only a cpp:namespace directive, then the current scope will be reset to global scope. That is, .. cpp:namespace:: A::B is equivalent to:

.. cpp:namespace:: nullptr

.. cpp:namespace-push:: A::B

1.4 新版功能.

Info field lists

All the C++ directives for declaring entities support the following info fields (see also Info field lists):

  • tparam: Description of a template parameter.

The cpp:function directive additionally supports the following fields:

  • paramparameterargargument:描述一个参数。

  • returnsreturn:描述一个返回值。

  • retvalretvals:替代 returns,用于描述函数的结果。

  • throws, throw, exception: Description of a possibly thrown exception.

4.3 新版功能: retval 字段类型。

Cross-referencing

These roles link to the given declaration types:

:cpp:any:
:cpp:class:
:cpp:struct:
:cpp:func:
:cpp:member:
:cpp:var:
:cpp:type:
:cpp:concept:
:cpp:enum:
:cpp:enumerator:

Reference a C++ declaration by name (see below for details). The name must be properly qualified relative to the position of the link.

2.0 新版功能: The cpp:struct role as alias for the cpp:class role.

Note on References with Templates Parameters/Arguments

These roles follow the Sphinx 交叉引用语法 rules. This means care must be taken when referencing a (partial) template specialization, e.g. if the link looks like this: :cpp:class:`MyClass<int>`. This is interpreted as a link to int with a title of MyClass. In this case, escape the opening angle bracket with a backslash, like this: :cpp:class:`MyClass\<int>`.

When a custom title is not needed it may be useful to use the roles for inline expressions, cpp:expr and cpp:texpr, where angle brackets do not need escaping.

Declarations without template parameters and template arguments

For linking to non-templated declarations the name must be a nested name, e.g., f or MyClass::f.

Overloaded (member) functions

When a (member) function is referenced using just its name, the reference will point to an arbitrary matching overload. The cpp:any and cpp:func roles use an alternative format, which simply is a complete function declaration. This will resolve to the exact matching overload. As example, consider the following class declaration:

class C
void f(double d) const
void f(double d)
void f(int i)
void f()

References using the cpp:func role:

Note that the add_function_parentheses configuration variable does not influence specific overload references.

Templated declarations

Assume the following declarations.

class Wrapper
template<typename TOuter>
class Outer
template<typename TInner>
class Inner

In general the reference must include the template parameter declarations, and template arguments for the prefix of qualified names. For example:

  • template\<typename TOuter> Wrapper::Outer (template<typename TOuter> Wrapper::Outer)

  • template\<typename TOuter> template\<typename TInner> Wrapper::Outer<TOuter>::Inner (template<typename TOuter> template<typename TInner> Wrapper::Outer<TOuter>::Inner)

Currently the lookup only succeed if the template parameter identifiers are equal strings. That is, template\<typename UOuter> Wrapper::Outer will not work.

As a shorthand notation, if a template parameter list is omitted, then the lookup will assume either a primary template or a non-template, but not a partial template specialisation. This means the following references work as well:

(Full) Template Specialisations

Assume the following declarations.

template<typename TOuter>
class Outer
template<typename TInner>
class Inner
template<>
class Outer<int>
template<typename TInner>
class Inner
template<>
class Inner<bool>

In general the reference must include a template parameter list for each template argument list. The full specialisation above can therefore be referenced with template\<> Outer\<int> (template<> Outer<int>) and template\<> template\<> Outer\<int>::Inner\<bool> (template<> template<> Outer<int>::Inner<bool>). As a shorthand the empty template parameter list can be omitted, e.g., Outer\<int> (Outer<int>) and Outer\<int>::Inner\<bool> (Outer<int>::Inner<bool>).

Partial Template Specialisations

Assume the following declaration.

template<typename T>
class Outer<T*>

References to partial specialisations must always include the template parameter lists, e.g., template\<typename T> Outer\<T*> (template<typename T> Outer<T*>). Currently the lookup only succeed if the template parameter identifiers are equal strings.

Configuration Variables

See Options for the C++ domain.

标准域

所谓的 “standard” 域收集了所有不需要有自己的域的标记。它的指令和角色不以域名为前缀。

标准域也是使用 add_object_type() API 添加的自定义对象描述的地方。

有一套允许记录命令行程序的指令:

.. option:: name args, name args, ...

描述了一个命令行参数或开关。选项参数名称应该用角括号括起来。示例

.. option:: dest_dir

   Destination directory.

.. option:: -m <module>, --module <module>

   Run a module as a script.

该指令将为给定的选项创建交叉引用目标,可通过 option 来引用(在例子中,你会使用 :option:`dest_dir:option:`-m`:option:`--module`)。

cmdoption 指令是 option 指令的一个废弃的别名。

.. envvar:: name

描述文档中的代码或程序使用或定义的环境变量。可以通过 envvar 来引用。

.. program:: name

py:currentmodule 一样,这个指令不产生输出。相反,它的作用是通知 Sphinx,所有下面的 option 指令都记录了名为 name 的程序的选项。

如果你使用 program,你必须在你的 option 角色中用程序名称来限定引用,所以如果你有以下情况

.. program:: rm

.. option:: -r

   Work recursively.

.. program:: svn

.. option:: -r <revision>

   Specify the revision to work upon.

那么 :option:`rm -r 将指第一个选项,而 :option:`svn -r` 将指第二个选项。

如果 None 被传递给参数,该指令将重置当前的程序名称。

程序名称可以包含空格(以备你想单独记录子命令,如 svn addsvn commit)。

0.5 新版功能.

还有一个非常通用的对象描述指令,它不与任何域相联系:

.. describe:: text
.. object:: text

该指令产生的格式与域所提供的特定格式相同,但不创建索引条目或交叉引用目标。例如

.. describe:: PAPER

   You can set this variable to select a paper size.

The JavaScript Domain

The JavaScript domain (name js) provides the following directives:

.. js:module:: name

This directive sets the module name for object declarations that follow after. The module name is used in the global module index and in cross references. This directive does not create an object heading like py:class would, for example.

By default, this directive will create a linkable entity and will cause an entry in the global module index, unless the noindex option is specified. If this option is specified, the directive will only update the current module name.

1.6 新版功能.

.. js:function:: name(signature)

Describes a JavaScript function or method. If you want to describe arguments as optional use square brackets as documented for Python signatures.

You can use fields to give more details about arguments and their expected types, errors which may be thrown by the function, and the value being returned:

.. js:function:: $.getJSON(href, callback[, errback])

   :param string href: An URI to the location of the resource.
   :param callback: Gets called with the object.
   :param errback:
       Gets called in case the request fails. And a lot of other
       text so we need multiple lines.
   :throws SomeError: For whatever reason in that case.
   :returns: Something.

This is rendered as:

$.getJSON(href, callback[, errback])
参数
  • href (string()) – An URI to the location of the resource.

  • callback – Gets called with the object.

  • errback – Gets called in case the request fails. And a lot of other text so we need multiple lines.

抛出

SomeError() – For whatever reason in that case.

返回

Something.

.. js:method:: name(signature)

This directive is an alias for js:function, however it describes a function that is implemented as a method on a class object.

1.6 新版功能.

.. js:class:: name

Describes a constructor that creates an object. This is basically like a function but will show up with a class prefix:

.. js:class:: MyAnimal(name[, age])

   :param string name: The name of the animal
   :param number age: an optional age for the animal

This is rendered as:

class MyAnimal(name[, age])
参数
  • name (string()) – The name of the animal

  • age (number()) – an optional age for the animal

.. js:data:: name

Describes a global variable or constant.

.. js:attribute:: object.name

Describes the attribute name of object.

提供这些角色是为了指代所描述的对象:

:js:mod:
:js:func:
:js:meth:
:js:class:
:js:data:
:js:attr:

reStructuredText 域

reStructuredText 域(名称为 rst)提供以下指令:

.. rst:directive:: name

描述了一个 reST 指令。name 可以是一个单一的指令名称或实际的指令语法(.. 前缀和 :: 后缀),其参数将被不同地呈现。 例如

.. rst:directive:: foo

   Foo description.

.. rst:directive:: .. bar:: baz

   Bar description.

将被渲染为:

.. foo::

Foo description.

.. bar:: baz

Bar description.

.. rst:directive:option:: name

描述了 reST 指令的一个选项。name 可以是一个单独的选项名称,也可以是带有参数的选项名称,用冒号(:)分开。例如

.. rst:directive:: toctree

   .. rst:directive:option:: caption: caption of ToC

   .. rst:directive:option:: glob

将被渲染为:

.. toctree::
:caption: caption of ToC
:glob:

选项

:type: description of argument (text)

描述 选项 值的类型。

例如

.. rst:directive:: toctree

   .. rst:directive:option:: maxdepth
      :type: integer or no value

2.1 新版功能.

.. rst:role:: name

描述了一个 reST 角色。比如说

.. rst:role:: foo

   Foo description.

将被渲染为:

:foo:

Foo description.

提供这些角色是为了指代所描述的对象:

:rst:dir:
:rst:role:

数学域

数学域(名称为 math)提供了以下 角色:

:math:numref:

用于通过标签交叉引用由 math 指令定义的方程的角色。例如

.. math:: e^{i\pi} + 1 = 0
   :label: euler

Euler's identity, equation :math:numref:`euler`, was elected one of the
most beautiful mathematical formulas.

1.8 新版功能.

更多域

sphinx-contrib 仓库包含了更多可作为扩展的域;目前有 AdaCoffeeScriptErlangHTTPLassoMATLABPHPRuby 域。另外还有 ChapelCommon LispdqnGoJinjaOperationScala 等域。