[C++-sig] Re: wrapping boost::optional

Neal D. Becker ndbecker2 at verizon.net
Wed Jul 28 18:50:05 CEST 2004


David Abrahams wrote:

> "Neal D. Becker" <ndbecker2 at verizon.net> writes:
> 
>> What would be better, though, is that if the option is not initialized,
>> it
>> should return None in response to get.  That would be more pythonic, no?
>> Problem is, I don't know how to do that.  Any hints?
> 
> template<typename T>
> inline object get (boost::optional<T>& o) {
>   return o ? object() : object(o.get());
> }
> 
> You'll have some issues with policies and ownership if you ever want
> to wrap optional<T*> or optional<T&>, but this should be enough to get
> you started.
> 

Thanks.  Doesn't seem to work though:
>>> o=optional_wrap.opt_int()
>>> o
<optional_wrap.opt_int object at 0x550737d4>
>>> o.get()
1426232544

Here is the complete code:
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/python/init.hpp>
#include <boost/python/operators.hpp>

using namespace boost::python;

template<typename T>
inline void set (boost::optional<T>& o, T x) {
  o = x;
}
  

template<typename T>
inline object get (boost::optional<T>& o) {
  return o ? object() : object(o.get());
}

#define OPTIONAL(T)\
  class_<boost::optional<T> >("opt_"#T) \
    .def ("set", &set<T>) \
    .def ("get", &get<T>) \
    .def (!(self)) \
    ;

BOOST_PYTHON_MODULE(optional_wrap)
{

  OPTIONAL(int)
  
  OPTIONAL(double)
}





More information about the Cplusplus-sig mailing list