Sparkofska
Sparkofska

Reputation: 1320

How to get pointer out of boost::optional?

I want to get the pointer that is stored in my boost::optional. Is there a preferred way to do this? What I got now looks quite cumbersome (dereference and reference again):


// a function I want to call
void processFrame(const Frame* frame) { ... }

// this is how I get my optional
boost::optional<Frame> frame = video.getFrame();

// this is my call so far, which I am not satisfied with (looks strange)
processFrame(frame ? &(*frame) : nullptr);

Upvotes: 1

Views: 702

Answers (1)

rafix07
rafix07

Reputation: 20918

You can use get_ptr() method:

// Returns a pointer to the value if this is initialized, otherwise,
// returns NULL.
// No-throw
pointer_const_type get_ptr() const { return m_initialized ? get_ptr_impl() : 0 ; }
pointer_type       get_ptr()       { return m_initialized ? get_ptr_impl() : 0 ; }

then your invocation is reduced to:

processFrame(frame.get_ptr());

Demo

Upvotes: 1

Related Questions