[C++-sig] Re: iterator interface question

Raoul Gough RaoulGough at yahoo.co.uk
Fri Jan 30 18:03:49 CET 2004


"Neal D. Becker" <nbecker at hns.com> writes:

> My question is really generic.  I have lots of C++ algorithms written in STL
> style.  They pass containers as pairs of iterators.
>
> Consider the generic algorithm X:
>
> template<typename in_t, typename out_t>
> void X (in_t in, in_t inend, out_t out);
>
> Now I have exposed std::vector<double> (for example) to python, so python
> can create a std::vector<double> like:
>
> x = DVec (10)
>
> But what I want to know, how can python call algorithm X, which expects a
> pair of iterators?
>
> Since STL became widely used, it is increasingly common to write algorithms
> in this style, so I hope there is a way to do this.

Well, you've got two problems as I see it. Firstly, how to get the
address of a function template instance, and secondly, how to pass an
iterator between Python and C++.

If I understand Dave's post in this thread, he says you can't take the
address of a function in the standard library. AFAIK, this is not
really a problem in practice. The potential problems are just the
usual overload resolution/template argument specification. If you have
overloaded functions, you need to cast the function to the correct
type:

e.g. def (static_cast<void (*)()>(overloaded_function));

This looks worse for member functions. For function templates, you
have to select a particular instance of the template, e.g.

def (X<std::vector<double>::iterator, some_type>);

This is tedious since it doesn't have automatic template argument
deduction.

The second problem of passing iterators to/from Python is just a
question of deciding how to pass them around. For instance, you might
be able to expose them like any other types:

class_<std::deque<double>::iterator ...

so that you can pass them around. However, I forsee problems with
std::vector if your standard library uses pointers for iterators
here. Probably a better solution would be to write a simple
iterator_range wrapper that contains two C++ iterators, expose that to
Python and use simple forwarding functions for your algorithms.

-- 
Raoul Gough.
export LESS='-X'





More information about the Cplusplus-sig mailing list