Skip to content

std::variant of integral and bool populates wrong alternative #1625

@johnshaw

Description

@johnshaw

Populating a variant containing an integral type and a bool from a Python bool may select the wrong alternative, depending on the ordering of alternatives.

Consider the function void foo(std::variant<int, bool> v). When called from Python with the expression foo(True), the value v in C++ will end up with the int alternative populated with a value of 1. If the order of the alternatives are swapped such that bool occurs before int, the boolean alternative will be populated, as expected.

The reason this occurs is that the type_caster for integral types is defined for all types satisfying is_arithmetic, which bool satisfies, combined with the fact that loading a bool into an integer type is not considered a "conversion" in the context of the load method, so it is selected on the first pass.

I think this should be improved so that bool doesn't match the arithmetic type caster on the first pass.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions