{"id":193,"date":"2013-01-13T08:51:29","date_gmt":"2013-01-13T16:51:29","guid":{"rendered":"http:\/\/martinecker.com\/martincodes\/?p=193"},"modified":"2013-01-13T08:51:49","modified_gmt":"2013-01-13T16:51:49","slug":"cplusplus11-wrap-pattern","status":"publish","type":"post","link":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/","title":{"rendered":"C++11 Wrap Pattern"},"content":{"rendered":"<p>Herb Sutter gave a great talk at the C++ and Beyond 2012 conference on <a href=\"http:\/\/channel9.msdn.com\/Shows\/Going+Deep\/C-and-Beyond-2012-Herb-Sutter-Concurrency-and-Parallelism\" target=\"_blank\">concurrency in C++11<\/a>.<\/p>\n<p>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.<br \/>\nThe pattern basically looks like this:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\ntemplate &lt;typename T&gt;\r\nclass wrap\r\n{\r\npublic:\r\n\twrap(T wrapped = T{}) : m_wrapped{wrapped}\r\n\t{}\r\n\t\r\n\t\/\/ operator() takes any code that accepts a wrapped T\r\n\t\/\/ will usually be a lambda\r\n\ttemplate &lt;typename F&gt;\r\n\tauto operator()(F func) -&gt; decltype(func(m_wrapped))\r\n\t{\r\n\t\t\/\/ do any pre-function call wrapper work \r\n\t\tauto result = func(m_wrapped);\r\n\t\t\/\/ do any post-function call wrapper work \r\n\t\treturn result;\r\n\t}\r\n\t\r\nprivate:\r\n\tT m_wrapped;\r\n\t\/\/ ... other state required by wrapper\r\n};\r\n<\/pre>\n<p>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.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nwrap&lt;X&gt; wrapper;\r\nwrapper([](X&amp; x)\r\n{\r\n\tx.call_something(foo, bar);\r\n\tx.do_something_else();\r\n\tstd::cout &lt;&lt; x.print() &lt;&lt; std::endl;\r\n});\r\n<\/pre>\n<p>A concrete example of using this pattern is a monitor wrapper class, which is similar to the synchronized keyword in Java.<br \/>\nA 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.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\ntemplate &lt;typename T&gt;\r\nclass monitor\r\n{\r\npublic:\r\n\tmonitor(T wrapped = T{}) : m_wrapped{wrapped}\r\n\t{}\r\n\t\r\n\ttemplate &lt;typename F&gt;\r\n\tauto operator()(F func) -&gt; decltype(func(m_wrapped))\r\n\t{\r\n\t\tstd::lock_guard&lt;mutex&gt; lock{m_mutex};\r\n\t\treturn func(m_wrapped);\r\n\t}\r\n\r\nprivate:\r\n\tmutable T m_wrapped;\r\n\tmutable std::mutex m_mutex;\r\n};\r\n<\/pre>\n<p>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&.<\/p>\n<p>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.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nmonitor&lt;string&gt; s = &quot;start\\n&quot;;\r\nstd::vector&lt;std::future&lt;void&gt;&gt; tasks;\r\n\r\n\/\/ start a bunch of tasks\r\nfor (int i = 0; i &lt; 5; ++i)\r\n{\r\n\ttasks.push_back(async([&amp;,i]\r\n\t{\r\n\t\t\/\/ single transaction, synchronized modification of s\r\n\t\ts([=](string&amp; s)\r\n\t\t{\r\n\t\t\ts += &quot;transaction &quot; + to_string(i) + &quot; of 5&quot;;\r\n\t\t\ts += '\\n';\r\n\t\t});\r\n\t\t\r\n\t\t\/\/ do some more work\r\n\t\t\r\n\t\t\/\/ single transaction, synchronized read of s\r\n\t\ts([](string&amp; s)\r\n\t\t{\r\n\t\t\tstd::cout &lt;&lt; s;\r\n\t\t});\r\n\t});\r\n}\r\n\r\n\/\/ join all tasks\r\nfor (auto&amp; task : tasks)\r\n\ttask.wait();\r\n<\/pre>\n<p>Note that T used in wrap<T> or monitor<T> 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.<br \/>\nSo it is perfectly valid to do:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nmonitor&lt;ostream&amp;&gt; sync_cout{std::cout};\r\n\r\nsync_cout([=](ostream&amp; cout)\r\n{\r\n\tcout &lt;&lt; &quot;Writing stuff to cout...&quot; &lt;&lt; std::endl;\r\n\tcout &lt;&lt; &quot;in a synchronized way&quot; &lt;&lt; std::endl;\r\n});\r\n<\/pre>\n<p>That's a wrap, folks! \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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 &hellip; <a href=\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"footnotes":""},"categories":[10],"tags":[23,14,16,15],"class_list":["post-193","post","type-post","status-publish","format-standard","hentry","category-c","tag-c","tag-c11","tag-pattern","tag-wrap"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.12 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>C++11 Wrap Pattern - Martin Codes<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"C++11 Wrap Pattern - Martin Codes\" \/>\n<meta property=\"og:description\" content=\"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 &hellip; Continue reading &rarr;\" \/>\n<meta property=\"og:url\" content=\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/\" \/>\n<meta property=\"og:site_name\" content=\"Martin Codes\" \/>\n<meta property=\"article:published_time\" content=\"2013-01-13T16:51:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2013-01-13T16:51:49+00:00\" \/>\n<meta name=\"author\" content=\"Martin Ecker\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Martin Ecker\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/\",\"url\":\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/\",\"name\":\"C++11 Wrap Pattern - Martin Codes\",\"isPartOf\":{\"@id\":\"http:\/\/martinecker.com\/martincodes\/#website\"},\"datePublished\":\"2013-01-13T16:51:29+00:00\",\"dateModified\":\"2013-01-13T16:51:49+00:00\",\"author\":{\"@id\":\"http:\/\/martinecker.com\/martincodes\/#\/schema\/person\/2ad254c988c5aaef13e54a1cadde5816\"},\"breadcrumb\":{\"@id\":\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/martinecker.com\/martincodes\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"C++11 Wrap Pattern\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/martinecker.com\/martincodes\/#website\",\"url\":\"http:\/\/martinecker.com\/martincodes\/\",\"name\":\"Martin Codes\",\"description\":\"Ramblings from a video game\/graphics programmer on anything coding- or graphics-related\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/martinecker.com\/martincodes\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"http:\/\/martinecker.com\/martincodes\/#\/schema\/person\/2ad254c988c5aaef13e54a1cadde5816\",\"name\":\"Martin Ecker\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/martinecker.com\/martincodes\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/7dfd53e699c35d22210a3c63e4b3e2cfae66f49029b0cde5f3c9d86847471d7a?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/7dfd53e699c35d22210a3c63e4b3e2cfae66f49029b0cde5f3c9d86847471d7a?s=96&d=mm&r=g\",\"caption\":\"Martin Ecker\"},\"url\":\"http:\/\/martinecker.com\/martincodes\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"C++11 Wrap Pattern - Martin Codes","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/","og_locale":"en_US","og_type":"article","og_title":"C++11 Wrap Pattern - Martin Codes","og_description":"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 &hellip; Continue reading &rarr;","og_url":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/","og_site_name":"Martin Codes","article_published_time":"2013-01-13T16:51:29+00:00","article_modified_time":"2013-01-13T16:51:49+00:00","author":"Martin Ecker","twitter_misc":{"Written by":"Martin Ecker","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/","url":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/","name":"C++11 Wrap Pattern - Martin Codes","isPartOf":{"@id":"http:\/\/martinecker.com\/martincodes\/#website"},"datePublished":"2013-01-13T16:51:29+00:00","dateModified":"2013-01-13T16:51:49+00:00","author":{"@id":"http:\/\/martinecker.com\/martincodes\/#\/schema\/person\/2ad254c988c5aaef13e54a1cadde5816"},"breadcrumb":{"@id":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/martinecker.com\/martincodes\/cplusplus11-wrap-pattern\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/martinecker.com\/martincodes\/"},{"@type":"ListItem","position":2,"name":"C++11 Wrap Pattern"}]},{"@type":"WebSite","@id":"http:\/\/martinecker.com\/martincodes\/#website","url":"http:\/\/martinecker.com\/martincodes\/","name":"Martin Codes","description":"Ramblings from a video game\/graphics programmer on anything coding- or graphics-related","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/martinecker.com\/martincodes\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"http:\/\/martinecker.com\/martincodes\/#\/schema\/person\/2ad254c988c5aaef13e54a1cadde5816","name":"Martin Ecker","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/martinecker.com\/martincodes\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/7dfd53e699c35d22210a3c63e4b3e2cfae66f49029b0cde5f3c9d86847471d7a?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/7dfd53e699c35d22210a3c63e4b3e2cfae66f49029b0cde5f3c9d86847471d7a?s=96&d=mm&r=g","caption":"Martin Ecker"},"url":"http:\/\/martinecker.com\/martincodes\/author\/admin\/"}]}},"_links":{"self":[{"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/posts\/193","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/comments?post=193"}],"version-history":[{"count":6,"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/posts\/193\/revisions"}],"predecessor-version":[{"id":199,"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/posts\/193\/revisions\/199"}],"wp:attachment":[{"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/media?parent=193"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/categories?post=193"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/martinecker.com\/martincodes\/wp-json\/wp\/v2\/tags?post=193"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}