@@ -1007,6 +1007,12 @@ class class_ : public detail::generic_type {
10071007 return *this ;
10081008 }
10091009
1010+ template <typename ... Args, typename ... Extra>
1011+ class_ &def (detail::init_factory<Args...> &&init, const Extra&... extra) {
1012+ std::move (init).execute (*this , extra...);
1013+ return *this ;
1014+ }
1015+
10101016 template <typename Func> class_& def_buffer (Func &&func) {
10111017 struct capture { Func func; };
10121018 capture *ptr = new capture { std::forward<Func>(func) };
@@ -1155,6 +1161,8 @@ class class_ : public detail::generic_type {
11551161 init_holder_helper (inst, (const holder_type *) holder_ptr, inst->value );
11561162 }
11571163
1164+ template <typename , typename , typename ...> friend struct detail ::init_factory;
1165+
11581166 static void dealloc (PyObject *inst_) {
11591167 instance_type *inst = (instance_type *) inst_;
11601168 if (inst->holder_constructed )
@@ -1295,7 +1303,177 @@ template <typename... Args> struct init_alias {
12951303 cl.def (" __init__" , [](Alias *self_, Args... args) { new (self_) Alias (args...); }, extra...);
12961304 }
12971305};
1306+ template <typename Func, typename Return, typename ... Args> struct init_factory {
1307+ private:
1308+ using PlainReturn = typename std::remove_pointer<Return>::type;
1309+ using ForwardReturn = typename std::add_rvalue_reference<Return>::type;
1310+
1311+ template <typename Class> using Cpp = typename Class::type;
1312+ template <typename Class> using Alias = typename Class::type_alias;
1313+ template <typename Class> using Inst = typename Class::instance_type;
1314+ template <typename Class> using Holder = typename Class::holder_type;
1315+
1316+ template <typename Class, typename SFINAE = void > struct alias_constructible : std::false_type {};
1317+ template <typename Class> struct alias_constructible <Class, enable_if_t <Class::has_alias && all_of<
1318+ std::is_convertible<Return, Alias<Class>>, std::is_constructible<Alias<Class>, Alias<Class> &&>,
1319+ std::is_convertible<Return, Cpp<Class>>, std::is_constructible<Cpp<Class>, Cpp<Class> &&>>::value>>
1320+ : std::true_type {};
1321+
1322+ // We accept a return value in the following categories, in order of precedence:
1323+ struct wraps_pointer_tag {};
1324+ struct wraps_holder_tag {};
1325+ struct wraps_pyobject_tag {};
1326+ struct wraps_alias_tag {};
1327+ struct wraps_value_tag {};
1328+ struct invalid_factory_return_type {};
1329+
1330+ // Resolve the combination of Class and Return value to exactly one of the above tags:
1331+ template <typename Class> using factory_type =
1332+ // a pointer of the actual or a derived type:
1333+ conditional_t <std::is_pointer<Return>::value && std::is_base_of<Cpp<Class>, PlainReturn>::value,
1334+ wraps_pointer_tag,
1335+ // a holder:
1336+ conditional_t <std::is_convertible<Holder<Class>, Return>::value,
1337+ wraps_holder_tag,
1338+ // a python object (with compatible type checking and failure at runtime):
1339+ conditional_t <std::is_convertible<Return, handle>::value,
1340+ wraps_pyobject_tag,
1341+ // Two accept-by-value versions: the first is for classes with an alias where the returned value
1342+ // is convertible to either the alias or the value:
1343+ conditional_t <alias_constructible<Class>::value,
1344+ wraps_alias_tag,
1345+ // Accept-by-value with no alias or a return value not convertible to the alias (e.g. a
1346+ // Cpp<Class> value itself):
1347+ conditional_t <std::is_convertible<Return, Cpp<Class>>::value && std::is_constructible<Cpp<Class>, Cpp<Class> &&>::value,
1348+ wraps_value_tag,
1349+ invalid_factory_return_type>>>>>;
12981350
1351+ public:
1352+ // Constructor: takes the function/lambda to call
1353+ init_factory (Func &&f) : f{std::move (f)} {}
1354+
1355+ template <typename Class, typename ... Extra>
1356+ void execute (Class &cl, const Extra&... extra) && {
1357+ // Some checks against various types of failure that we can detect at compile time:
1358+ static_assert (!std::is_same<factory_type<Class>, invalid_factory_return_type>::value,
1359+ " pybind11::init_factory(): wrapped factory function must return a compatible pointer, "
1360+ " holder, python object, or value" );
1361+
1362+ handle cl_type (cl);
1363+ #if defined(PYBIND11_CPP14) || defined(_MSC_VER)
1364+ cl.def (" __init__" , [cl_type, func = std::move (f)]
1365+ #else
1366+ Func func = std::move (f);
1367+ cl.def (" __init__" , [cl_type, func]
1368+ #endif
1369+ (handle self, Args... args) {
1370+ auto *inst = (Inst<Class> *) self.ptr ();
1371+ construct<Class>(inst, func (std::forward<Args>(args)...), cl_type, factory_type<Class>());
1372+ }, extra...);
1373+ }
1374+
1375+ protected:
1376+ template <typename Class> static void dealloc (Inst<Class> *self) {
1377+ // Reset/unallocate the existing values
1378+ clear_instance ((PyObject *) self);
1379+ self->value = nullptr ;
1380+ self->owned = true ;
1381+ self->holder_constructed = false ;
1382+ }
1383+
1384+ template <typename Class>
1385+ static void construct (Inst<Class> *self, Cpp<Class> *result, handle /* cl_type*/ , wraps_pointer_tag) {
1386+ // We were given a pointer to CppClass (or some derived type); dealloc the existing value
1387+ // and replace it with the given pointer; the dispatcher will then set up the holder for us
1388+ // after we return from the lambda.
1389+ dealloc<Class>(self);
1390+ self->value = result;
1391+ register_instance (self);
1392+ }
1393+
1394+ template <typename Class>
1395+ static void construct (Inst<Class> *self, Holder<Class> holder, handle /* cl_type*/ , wraps_holder_tag) {
1396+ // We were returned a holder; copy its pointer, and move/copy the holder into place.
1397+ dealloc<Class>(self);
1398+ self->value = holder_helper<Holder<Class>>::get (holder);
1399+ Class::init_holder ((PyObject *) self, &holder);
1400+ register_instance (self);
1401+ }
1402+
1403+ template <typename Class>
1404+ static void construct (Inst<Class> *self, handle result, handle cl_type, wraps_pyobject_tag tag) {
1405+ // We were given a raw handle; steal it and forward to the py::object version
1406+ construct<Class>(self, reinterpret_steal<object>(result), cl_type, tag);
1407+ }
1408+ template <typename Class>
1409+ static void construct (Inst<Class> *self, object result, handle /* cl_type*/ , wraps_pyobject_tag) {
1410+ // Lambda returned a py::object (or something derived from it)
1411+
1412+ // Make sure we actually got something
1413+ if (!result)
1414+ throw type_error (" __init__() factory function returned a null python object" );
1415+
1416+ auto *result_inst = (Inst<Class> *) result.ptr ();
1417+ auto type = Py_TYPE (self);
1418+
1419+ // Make sure the factory function gave us exactly the right type (we don't allow
1420+ // up/down-casting here):
1421+ if (Py_TYPE (result_inst) != type)
1422+ throw type_error (std::string (" __init__() factory function should return '" ) + type->tp_name +
1423+ " ', not '" + Py_TYPE (result_inst)->tp_name + " '" );
1424+ // The factory function must give back a unique reference:
1425+ if (result.ref_count () != 1 )
1426+ throw type_error (" __init__() factory function returned an object with multiple references" );
1427+ // Guard against accidentally specifying a reference r.v. policy or similar:
1428+ if (!result_inst->owned )
1429+ throw type_error (" __init__() factory function returned an unowned reference" );
1430+
1431+ // Steal the instance internals:
1432+ dealloc<Class>(self);
1433+ std::swap (self->value , result_inst->value );
1434+ std::swap (self->weakrefs , result_inst->weakrefs );
1435+ if (type->tp_dictoffset != 0 )
1436+ std::swap (*_PyObject_GetDictPtr ((PyObject *) self), *_PyObject_GetDictPtr ((PyObject *) result_inst));
1437+ // Now steal the holder
1438+ Class::init_holder ((PyObject *) self, &result_inst->holder );
1439+ // Find the instance we just stole and update its PyObject from `result` to `self`
1440+ auto range = get_internals ().registered_instances .equal_range (self->value );
1441+ for (auto it = range.first ; it != range.second ; ++it) {
1442+ if (type == Py_TYPE (it->second )) {
1443+ it->second = self;
1444+ break ;
1445+ }
1446+ }
1447+ }
1448+
1449+ // wrap return-by-value, version 1: returns a cpp object (or something convertible to it) by
1450+ // value. (Returned values convertible to the alias class (if any) use the next version.)
1451+ template <typename Class>
1452+ static void construct (Inst<Class> *self, Cpp<Class> result, handle /* cl_type*/ , wraps_value_tag) {
1453+ new (self->value ) Cpp<Class>(std::move (result));
1454+ }
1455+
1456+ // Same as above, but when an alias class is involved and the return value is convertible to the
1457+ // alias (which typically *won't* be called for direct CppClass return).
1458+ template <typename Class>
1459+ static void construct (Inst<Class> *self, Return &&result, handle cl_type, wraps_alias_tag) {
1460+ if (Py_TYPE (self) == (PyTypeObject *) cl_type.ptr ())
1461+ construct_alias<Class>(self, std::forward<Return>(result));
1462+ else
1463+ construct<Class>(self, std::forward<Return>(result), cl_type, wraps_value_tag ());
1464+ }
1465+ template <typename Class>
1466+ static void construct_alias (Inst<Class> *self, Alias<Class> result) {
1467+ new (self->value ) Alias<Class>(std::move (result));
1468+ }
1469+
1470+ Func f;
1471+ };
1472+ // Helper definition to infer the detail::init_factory template type from a callable object
1473+ template <typename Func, typename Return, typename ... Args>
1474+ init_factory<Func, Return, Args...> init_factory_decltype (Return (*)(Args...));
1475+ template <typename Func> using init_factory_t = decltype (init_factory_decltype<Func>(
1476+ (typename detail::remove_class<decltype (&std::remove_reference<Func>::type::operator ())>::type *) nullptr ));
12991477
13001478inline void keep_alive_impl (handle nurse, handle patient) {
13011479 /* Clever approach based on weak references taken from Boost.Python */
@@ -1332,6 +1510,19 @@ NAMESPACE_END(detail)
13321510
13331511template <typename ... Args> detail::init<Args...> init () { return detail::init<Args...>(); }
13341512template <typename ... Args> detail::init_alias<Args...> init_alias () { return detail::init_alias<Args...>(); }
1513+ // / Construct a factory function constructor wrapper from a vanilla function pointer
1514+ template <typename Return, typename ... Args>
1515+ detail::init_factory<Return (*)(Args...), Return, Args...> init_factory (Return (*f)(Args...)) {
1516+ return f;
1517+ }
1518+ // / Construct a factory function constructor wrapper from a lambda function (possibly with internal state)
1519+ template <typename Func, typename = detail::enable_if_t <
1520+ detail::satisfies_none_of<
1521+ typename std::remove_reference<Func>::type,
1522+ std::is_function, std::is_pointer, std::is_member_pointer
1523+ >::value>
1524+ >
1525+ detail::init_factory_t <Func> init_factory (Func &&f) { return std::move (f); }
13351526
13361527// / Makes a python iterator from a first and past-the-end C++ InputIterator.
13371528template <return_value_policy Policy = return_value_policy::reference_internal,
0 commit comments