Skip to content

Commit f9f3bd7

Browse files
authored
Use C++17 fold expressions when casting tuples and argument lists (pybind#2043)
This commit introduces the use of C++17-style fold expressions when casting tuples & the argument lists of functions. This change can improve performance of the resulting bindings: because fold expressions have short-circuiting semantics, pybind11 e.g. won't try to cast the second argument of a function if the first one failed. This is particularly effective when working with functions that have many overloads with long argument lists.
1 parent 6e39b76 commit f9f3bd7

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

include/pybind11/cast.h

+10
Original file line numberDiff line numberDiff line change
@@ -1432,9 +1432,14 @@ template <template<typename...> class Tuple, typename... Ts> class tuple_caster
14321432

14331433
template <size_t... Is>
14341434
bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
1435+
#ifdef __cpp_fold_expressions
1436+
if ((... || !std::get<Is>(subcasters).load(seq[Is], convert)))
1437+
return false;
1438+
#else
14351439
for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...})
14361440
if (!r)
14371441
return false;
1442+
#endif
14381443
return true;
14391444
}
14401445

@@ -1961,9 +1966,14 @@ class argument_loader {
19611966

19621967
template <size_t... Is>
19631968
bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1969+
#ifdef __cpp_fold_expressions
1970+
if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])))
1971+
return false;
1972+
#else
19641973
for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...})
19651974
if (!r)
19661975
return false;
1976+
#endif
19671977
return true;
19681978
}
19691979

0 commit comments

Comments
 (0)