views:

163

answers:

2

In my C++ code I have a class Foo with many methods taking a Bar type variable as an argument:

class Foo {
public:
  void do_this(Bar b);
  void do_that(Bar b);
  /* ... */
};

Bar has a number of constructors that create a new object from many common types such as int, std::string, float, etc:

class Bar {
public:
  Bar(int i);
  Bar(float f);
  Bar(std::string s);
  /* ... */
};

I wrapped this with Boost::Python and I'm now able to call my Foo methods using Python literals directly, as they get implicitly converted to Bar objects.

f = Foo()
f.do_this(5)
f.do_that("hello")

Now, I would like to be able to use also other Python types, such as tuples, like this:

f.do_that((1,2,3))

But I don't want to touch the original Bar definition, and I don't want to pollute my C++ library with Boost::Python stuff. I want to write a wrapper function in my binding code, but I just can't understand if this is possible and what is the correct way for doing this.

In other words: can I register a factory function to be used as an automatic conversion in Python?

A: 

Create some type TupleCollector with overridden "operator ,(int)" so you can write

f.do_that((TuppleCollector(), 1, 2, 3))

at last create conversion between TupleCollector and expected target

Dewfy
thank you, this is an interesting idea, but not what I'm looking for... I would like to use tuples directly. I managed to create a new constructor for Bar accepting tuples, but there's no implicit conversion going on, I have to write Bar((1,2,3)) explicitly. :|
UncleZeiv
Derive from tuples class and make any assignment of int you want. (operator, - is also applicable)
Dewfy
A: 

You can export function do_that which take boost::python::object param, check if param is a python tuple, extract data and pass it to object.

W55tKQbuRu28Q4xv