[C++-sig] Extract

Stefan Seefeld seefeld at sympatico.ca
Wed May 30 19:24:26 CEST 2007


Sean Ross-Ross wrote:
> I have a templated class PatameterList that mimics a c++ map or a python
> dict.
> it has a method
> 
> template<class T>
> void set( string name,  T item )
> 
> how can I add a method in that will extract any c++ class from python
> and put it into the PatameterList
> 
> I was thinking along the lines of 
> 
> adding a method 
> void my_set( PatameterList const& self,string, name,
> boost::python::object o)
> {
> self.set(name , extract< whatever > ( o ) );
> }
> ...
> class_< PatameterList > ( ...
> ...
> .def( "set" , &my_set )
> ...
> 
> where I don't know how to implement the "whatever" arg.

I'm a little confused, and I'm not sure what exactly you want to do (as you seem
to be mixing templates and types).

If ParameterList is a class template, you have to instantiate a type from it
in order to export ot to python. Once this is done, 'T' (and thus, 'whatever'),
are bound to specific types, so all the rest should 'just work':

template <typename T>
class ParameterList
{
public:
  void set(std::string const &name, T value);
...
};

void my_set(ParameterList<Foo> &list, std::string const &name, object value)
{ list.set(name, extract<Foo>(value));}

class_<ParameterList<Foo> >
  ...
  .def("set", my_set);


However, this my_set indirection shouldn't even be necessary, since the conversion
between Python and C++ of Foo objects is implicit (assuming Foo is properly exported).
The cases where you'd need an explicit conversion like this is when you want to pass
tuples, or lists, and you need to extract the elements one-by-one inside C++.

HTH,
		Stefan


-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list