[c++-sig]Python binding for templated constructor

Hi, I have a class with a generic constructor as follows : class X { indexes m_idx; template<class strategy> X(){ build_indexes<strategy>() }; My problem is that I am not able to figure out the syntax to export this constructor. Is the above class not well defined ?. Thanks. Sandeep

On 05/25/2010 01:58 PM, Sandeep Gupta wrote:
Hi, I have a class with a generic constructor as follows : class X { indexes m_idx; template<class strategy> X(){ build_indexes<strategy>() };
My problem is that I am not able to figure out the syntax to export this constructor. Is the above class not well defined ?.
That's a good question. I'm not sure if it's possible using boost::python::init, but here's a possible workaround: namespace bp = boost::python; template <typename strategy> static X construct_X() { // could also return registered smart pointer to X. return X<strategy>(); } BOOST_PYTHON_MODULE(example) { bp::class_<X>("X", bp::no_init) // no_init keeps bp from trying to call default ctor .def("__init__", bp::make_constructor(&construct_X<concrete_strategy>)) ; } I haven't tested that, but I think it should work. By the way, you'll get more responses to Boost.Python questions at the Python/C++-sig mailing list: cplusplus-sig@python.org Hope that helps! Jim Bosch

On Tue, May 25, 2010 at 9:23 PM, Jim Bosch <talljimbo@gmail.com> wrote:
On 05/25/2010 01:58 PM, Sandeep Gupta wrote:
Hi, I have a class with a generic constructor as follows : class X { indexes m_idx; template<class strategy> X(){ build_indexes<strategy>() };
My problem is that I am not able to figure out the syntax to export this constructor. Is the above class not well defined ?.
That's a good question. I'm not sure if it's possible using boost::python::init, but here's a possible workaround:
namespace bp = boost::python;
template <typename strategy> static X construct_X() { // could also return registered smart pointer to X. return X<strategy>(); }
BOOST_PYTHON_MODULE(example) { bp::class_<X>("X", bp::no_init) // no_init keeps bp from trying to call default ctor .def("__init__", bp::make_constructor(&construct_X<concrete_strategy>)) ; }
I haven't tested that, but I think it should work. By the way, you'll get more responses to Boost.Python questions at the Python/C++-sig mailing list:
cplusplus-sig@python.org
Hope that helps!
Jim Bosch
Thanks Jim. For now I just added an extra function to the class X because it was simpler. I didn't knew about no_init and make_constructor annotations. Would try out the construct_X approach separately in due course. Thanks for the tip to post to c++-sig mailing list as well. Thanks. -Sandeep
participants (2)
-
Jim Bosch
-
Sandeep Gupta