Improve constructor resolution in variant_caster

Currently, `py::int_(1).cast<variant<double, int>>()` fills the `double`
slot of the variant. This commit switches the loader to a 2-pass scheme
in order to correctly fill the `int` slot.
This commit is contained in:
Dean Moldovan
2017-05-10 11:15:17 +02:00
parent 93e3eac6f9
commit 94d0a9f7bc
3 changed files with 15 additions and 1 deletions

View File

@@ -315,6 +315,12 @@ struct variant_caster<V<Ts...>> {
bool load_alternative(handle, bool, type_list<>) { return false; }
bool load(handle src, bool convert) {
// Do a first pass without conversions to improve constructor resolution.
// E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
// slot of the variant. Without two-pass loading `double` would be filled
// because it appears first and a conversion is possible.
if (convert && load_alternative(src, false, type_list<Ts...>{}))
return true;
return load_alternative(src, convert, type_list<Ts...>{});
}