[C++-sig] Re: Some questions ...
David Abrahams
dave at boost-consulting.com
Tue Sep 9 16:41:47 CEST 2003
"Mike Thompson" <mike.thompson at day8.com.au> writes:
> "David Abrahams" wrote:
>> "Mike Thompson" writes:
>>
>> > Q2. The following function works, but I'm left wondering if there's not a
>> > better way. It takes a list of ints and returns the equivalent
>> > vector<int>.
>> >
>> > vector<int> makeVectorFromList(list l)
>> > {
>> > boost::python::object olen = l.attr("__len__")();
>> > int len = extract<int>(olen)();
>> >
>> > vector<int> ret(len);
>> >
>> > for (int i = 0; i < len; ++i) {
>> > extract<int> get_int(l[i]);
>> > if (!get_int.check()) {
>> > PyErr_SetString(PyExc_TypeError, "makeVectorFromList()
>> > expects a list of ints");
>> > throw error_already_set();
>> > }
>> > ret[i] = get_int();
>> > }
>> > return ret;
>> > }
>>
>> What about that approach would you like to see improved? In other
>> words, why are you left wondering if there's a "better way"?
>>
>
> I was wondering if I was missing a bit of existing magic like, say, this:
>
> vector<int> v = extract<vector<int> > (l)();
>
> Except, of course, I tried that and it didn't work.
>
> But I kept wondering if, by writing this function, I was reinventing a wheel
> already built, probably more elegantly.
>
> So I asked.
Well, Ralf has built the wheel that allows the above; see the
Boost.Python FAQ.
I guess I should ask myself why we don't provide that conversion as a
built-in primitive. It certainly seems doable.
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list