C++ Encapsulation with Visual Assist with Move Semantics

Two examples how to achieve encapsulation with move semantics:

Option 1: using std::move(this is not the most optional one, causes duplicate code and problems type deduction)

Here is a snippet script for visual assist to encapsulate a property:

$end$$SymbolType$ $GeneratedPropertyName$() const { return $SymbolName$; }
void $GeneratedPropertyName$(const $SymbolType$ &value) { $SymbolName$ = value; }
void $GeneratedPropertyName$($SymbolType$ &&value) { $SymbolName$ = std::move(value); }

The end results would be something like this:

// Get method

VECTOR2D Position() const { return position; }

// Set by copy, lvalue
void Position(const VECTOR2D &value) { position = value; }

// Set by move(notice that here the ownership of the rvalue is changed from the parameters to the new value
void Position(VECTOR2D &&value) { position = std::move(value); }

 

Option 2: using std::forward(preferable way less code and support for reference collapsing)

BUT the above has code duplication and not the best of options. You can use instead universal references and move semantics with std::forward:

Snippet for Visual Assist:

$end$$SymbolType$ $GeneratedPropertyName$() const { return $SymbolName$; }
template<typename T>
void $GeneratedPropertyName$(T &&value) { $SymbolName$ = std::forward<T>(value); }

The end results would be something like this:

// Get method

Aurora::Math::VECTOR2D Position() const { return position; }

// Handles both lvalue and rvalue references through universal references and reference collapsing
template<typename T>
void Position(T &&value) { position = std::forward<T>(value); }

More information on why this is this way:

Universal References in C++11—Scott Meyers

C++ Rvalue References Explained

C++11: PERFECT FORWARDING

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s