[C++-sig] implititly_convertible<>() difficulty
Jonathan Brandmeyer
jdbrandm at unity.ncsu.edu
Tue Jul 29 18:23:15 CEST 2003
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>();
}
------------ and this is what I want to accomplish ----------------
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from tuple_test import tuple_type
>>> x = tuple_type( 0.1, 3, 4)
>>> y = (2, 3, 4)
>>> z = tuple_type(y)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation
>>> z = x+y
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'tuple_type' and 'tuple'
More information about the Cplusplus-sig
mailing list