Skip to content

Documenting that the order of alternatives for variant types matters, and follows the same rules as overload resolution #2784

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/advanced/cast/stl.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ The ``visit_helper`` specialization is not required if your ``name::variant`` pr
a ``name::visit()`` function. For any other function name, the specialization must be
included to tell pybind11 how to visit the variant.

.. warning::

When converting a ``variant`` type, pybind11 follows the same rules as when
determining which function overload to call (:ref:`overload_resolution`), and
so the same caveats hold. In particular, the order in which the ``variant``'s
alternatives are listed is important, since pybind11 will try conversions in
this order. This means that, for example, when converting ``variant<int, bool>``,
the ``bool`` variant will never be selected, as any Python ``bool`` is already
an ``int`` and is convertible to a C++ ``int``. Changing the order of alternatives
(and using ``variant<bool, int>``, in this example) provides a solution.

.. note::

pybind11 only supports the modern implementation of ``boost::variant``
Expand Down
2 changes: 2 additions & 0 deletions docs/advanced/functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,8 @@ The default behaviour when the tag is unspecified is to allow ``None``.
not allow ``None`` as argument. To pass optional argument of these copied types consider
using ``std::optional<T>``

.. _overload_resolution:

Overload resolution order
=========================

Expand Down