[C++-sig] Re: implititly_convertible<>() difficulty

David Abrahams dave at boost-consulting.com
Tue Jul 29 21:44:12 CEST 2003


"Jonathan Brandmeyer" <jdbrandm at unity.ncsu.edu> writes:

> I have a C++ type that I want to construct from a python tuple, and use
> python tuples in it's place.  implicitly_convertible<Source, Target>()
> looked like the right thing, but it is not giving me the results that I had
> hoped.  A complete example of what I am trying to do follows.
>
> This particular run was tested with GCC 3.2.2 (mingw) with Boost.Python
> 1.30.0 and Python 2.2.2 on WinXP.
>
> Thanks for you help,
> Jonathan Brandmeyer
>
> --------------------- tuple_test.cpp------------------------
> #include <boost/python.hpp>
>
> class tuple_type
> {
>  private:
>  double x;
>  double y;
>  double z;
>  public:
>  tuple_type( double a=0.0, double b=0.0, double c=0.0)
>   : x(a), y(b), z(c) {}
>
>  tuple_type( boost::python::tuple sequence)
>  {
>   using boost::python::extract;
>
>   int i = extract<int>( sequence.attr("__len__"));
>   switch (i) {
>    case 3:
>     z = extract<double>( sequence[2]);
>     // FALLTHROUGH
>    case 2:
>     y = extract<double>( sequence[1]);
>     x = extract<double>( sequence[0]);
>     break;
>    default:
>     break;
>   }
>  }
>
>  tuple_type
>  operator+( const tuple_type& t) const
>  { return tuple_type( x+t.x, y+t.y, z+t.z); }
> };
>
> BOOST_PYTHON_MODULE( tuple_test)
> {
>  using namespace boost::python;
>
>  class_<tuple_type>( "tuple_type", init<double, double, double>())
>   .def( self + self)
>   ;
>
>  implicitly_convertible<tuple, tuple_type>();
> }

I'm not sure what's going wrong here, but could you try this instead?

#include <boost/python.hpp>

class tuple_type
{
 private:
 double x;
 double y;
 double z;
 public:
 tuple_type( double a=0.0, double b=0.0, double c=0.0)
  : x(a), y(b), z(c) {}

 tuple_type( boost::python::tuple sequence)
 {
  using boost::python::extract;

  int i = extract<int>( sequence.attr("__len__"));
  switch (i) {
   case 3:
    z = extract<double>( sequence[2]);
    // FALLTHROUGH
   case 2:
    y = extract<double>( sequence[1]);
    x = extract<double>( sequence[0]);
    break;
   default:
    break;
  }
 }

 tuple_type
 operator+( const tuple_type& t) const
 { return tuple_type( x+t.x, y+t.y, z+t.z); }
};

BOOST_PYTHON_MODULE( tuple_test)
{
 using namespace boost::python;

 class_<tuple_type>( "tuple_type", init<double, double, double>())
  .def( self + self)
  .def( self + other<tuple>())
  ;
}


-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list