C++11 Wrap Pattern

Herb Sutter gave a great talk at the C++ and Beyond 2012 conference on concurrency in C++11.

The talk had an interesting interlude on how to wrap all functions performed on an existing type T in order to inject any desired behavior, and that's what this post is all about.
The pattern basically looks like this:

template <typename T>
class wrap
{
public:
	wrap(T wrapped = T{}) : m_wrapped{wrapped}
	{}
	
	// operator() takes any code that accepts a wrapped T
	// will usually be a lambda
	template <typename F>
	auto operator()(F func) -> decltype(func(m_wrapped))
	{
		// do any pre-function call wrapper work 
		auto result = func(m_wrapped);
		// do any post-function call wrapper work 
		return result;
	}
	
private:
	T m_wrapped;
	// ... other state required by wrapper
};

This wrap class template can now be used by instantiating it and calling operator() on it with an anonymous lambda function that accepts the wrapped type as single argument.

wrap<X> wrapper;
wrapper([](X& x)
{
	x.call_something(foo, bar);
	x.do_something_else();
	std::cout << x.print() << std::endl;
});

A concrete example of using this pattern is a monitor wrapper class, which is similar to the synchronized keyword in Java.
A monitor wraps every function call (or a group of function calls) on an existing class in a mutex lock to make the class thread-safe.

template <typename T>
class monitor
{
public:
	monitor(T wrapped = T{}) : m_wrapped{wrapped}
	{}
	
	template <typename F>
	auto operator()(F func) -> decltype(func(m_wrapped))
	{
		std::lock_guard<mutex> lock{m_mutex};
		return func(m_wrapped);
	}

private:
	mutable T m_wrapped;
	mutable std::mutex m_mutex;
};

Note that m_wrapped is mutable, which is required so that func(m_wrapped) works if func takes the T as a non-const reference T&.

Mutable in C++11 means thread-safe, which means either bitwise const or internally synchronized. Our mutex lock guard guarantees that by the time the m_wrapped is used in func(m_wrapped) it will be internally sychronized, so making m_wrapped mutable is perfectly acceptable.

monitor<string> s = "start\n";
std::vector<std::future<void>> tasks;

// start a bunch of tasks
for (int i = 0; i < 5; ++i)
{
	tasks.push_back(async([&,i]
	{
		// single transaction, synchronized modification of s
		s([=](string& s)
		{
			s += "transaction " + to_string(i) + " of 5";
			s += '\n';
		});
		
		// do some more work
		
		// single transaction, synchronized read of s
		s([](string& s)
		{
			std::cout << s;
		});
	});
}

// join all tasks
for (auto& task : tasks)
	task.wait();

Note that T used in wrap or monitor could also be a reference, if you don't want to make a copy of T. This is useful for capturing stateful objects, such as std::cout.
So it is perfectly valid to do:

monitor<ostream&> sync_cout{std::cout};

sync_cout([=](ostream& cout)
{
	cout << "Writing stuff to cout..." << std::endl;
	cout << "in a synchronized way" << std::endl;
});

That's a wrap, folks! 🙂

Share and Enjoy !

0Shares
0 0

Cool Link Stash, November/December 2012

C++

Scott Meyers has a new article up on his blog on the distinction between std::move and std::forward and their use in move constructors.

Bit Twiddling hacks is a great and pretty long compilation of trickery with regards to manipulating bits directly.

ChaiScript is an ECMAScript/JavaScript-inspired scripting language for embedding in C++ programs.

ViennaCL is an open source C++ computing library for scientific computing (mostly for solving linear systems) with multiple backends for CUDA, OpenCL, and OpenMP.

Andrey Sinyakov posted some great, introductory slides on new C++11 features. It's a pretty good whirlwind tour of the new standard.

Maths

Making Things with Maths is a fantastic, dynamic HTML5 slide set on using mathematics to procedurally create cool stuff. This is a truly awesome set of slides. Highly recommended!

Iñigo Quilez, of demoscene fame but now working at Pixar, gives some insights into the procedurally generated moss in the Pixar movie Brave.

The Nature of Code by Daniel Shiffman is an excellent resource to learn about the mathematical principles often found in nature. It uses Processing.js and contains lots of cool dynamic and interactive demos.

This page on Rapidly-exploring Random Trees is a great resource on an interesting algorithm to explore paths in nonconvex high-dimensional spaces. Pretty interesting technique. I found this via a reference from Casey Muratori's post in his post on The Witness blog on Mapping the Island's Walkable Surfaces.

Graphics

Sean Barrett wrote a great article on Corners Don't Look Like That: Regarding Screenspace Ambient Occlusion. I think we should move past SSAO as an industry. Unfortunately, I don't really see yet how we can replace it except for with expensive options like voxel cone tracing that might not be feasible for all games on next-gen consoles.

Here's a cool deferred area lights demo implemented in WebGL/three.js. It's based on an older post on the gamedev.net forums.

Share and Enjoy !

0Shares
0 0

Cool Link Stash, October 2012

JavaScript & Web Development

Understanding JavaScript OOP is a great article on, well, understanding how OOP works in JavaScript. It's interesting because it's very different from how OOP is implemented in languages like C++, C#, or Java. JavaScript implements prototypical OOP similarly to Self.

pixleJET is a nifty online, in-browser development environment for HTML, CSS, and JavaScript.

The State of JavaScript is a good presentation on current developments in JavaScript, in particular with regards to ECMAScript 6.

Since I've been recently dabbling with the MVVM pattern in WPF, I was looking for ways to do MVVM in the web browser with JavaScript as well. There are quite a few libraries out there, but one that struck me as quite nice is Knockout. The project's site has really good online tutorials where you develop small websites using Knockout directly in the browser, kind of like how pixelJET works.

If Knockout.js is not your thing, there are plenty of other libraries that help implement any kind of MV* pattern you can imagine. A good way to choose between them is to read Journey Through the JavaScript MVC Jungle. The article references TodoMVC, which is a small todo web application implemented in a large number of MV* libraries.

C++

cppreference.com is a great site that is a reference of the all variants of standard C/C++ and their respective standard libraries, in particular C++98, C++03, C++11, C89, C99, and C11.

Scott Myers has a good article on rvalue references and how they can be something else in certain cases where the type gets deduced, as is the case in templates or when using the auto keyword. He proposes the term universal references for these cases. Read his interesting article in Overload 111.
He gave a presentation on the same topic and a video of it is available here.

There has been some interesting discussion on various C++ blogs lately on how to best pass parameters to functions in C++11 that is worth following. Here are the relevant links in order:

While I appreciate these discussions as a programming language nerd, it definitely shows that C++11 makes C++ a much more complicated language in many regards, especially if you want to use all of its features to maximum effect. Even in these early days of C++11 usage, we already notice some loopholes or missing pieces with the latest language features, such as rvalue references and perfect forwarding. I'm glad I don't have to teach C++11. That sounds like a nightmare.

Christian Plesner Hansen posted an excellent article explaining in-depth how the inverse square root hack works. That hack was made famous by its use in the Quake C code base. He not only shows how and why the hack works but also demonstrates how it can be modified to work for 64-bit floating point types (or really any arbitrary number of bits) and how it can be extended to not just work for the inverse square root (i.e. a power of -0.5) but for any power between -1 and 1.

Graphics

The Journal of Computer Graphics Techniques posted a new article on compressing the frame buffer called The Compact YCoCg Frame Buffer. The idea is to basically reduce the frame buffer storage requirements by converting fragments into the YCoCg color space (which is a luminance/chrominance color space) and then store the chrominance channels at a lower resolution since the human eye isn't as sensitive to chrominance variations as it is to luminance variations. There is also a WebGL demo and a video on the paper's web site.

Simon Yeung posted a nice article on his implementation of angle-based SSAO over at #AltDevBlogADay. You can find the same article on his personal blog.

Ben Weston posted a nice blog article dealing with optimizing Perlin noise evaluation by using 3D texture hardware. As opposed to doing multiple texture lookups that get lerped, this technique uses a single 3D texture lookup and uses hardware trilinear filtering to effectively get the same result as if multiple lookups had been done.

MeshLab is a nice, open source tool for doing various mesh simplification and cleanup tasks. It builds on the VCG Library and is available for Windows, Linux, Mac, and even phones.

John Chapman posted a great tutorial on pseudo lens flares last month that I missed.

I was looking for some more info on Poisson disk sampling recently and I stumbled upon an old article from 2008 on the topic that is really good.

Unity

Tim Cooper posted a must-read article on serialization in Unity. I really wish this was part of the docs because I had to find out all of this the hard way, and some of it is not immediately obvious.

Share and Enjoy !

0Shares
0 0