Sponsored By

Featured Blog | This community-written post highlights the best of what the game industry has to offer. Read more like it on the Game Developer Blogs.

Modern C++ lightweight binary RPC framework without code generation

In this article, I go over the foundations of a new C++ RPC framework that requires no code generation. Using Modern C++, with type traits, variadic templates, and some other tricks, the final API is surprisingly simple.

Rui Figueira, Blogger

June 8, 2016

49 Min Read

&lt;p&gt;This was initially posted on my blog at:&amp;nbsp;&amp;nbsp;&lt;a href=&quot;http://www.crazygaze.com/blog/2016/06/06/modern-c-lightweight-binary-rpc-framework-without-code-generation/&quot;&gt;http://www.crazygaze.com/blog/2016/06/06/modern-c-lightweight-binary-rpc-framework-without-code-generation/&lt;/a&gt;&lt;/p&gt; &lt;h1&gt;Table of Contents&lt;/h1&gt; &lt;ol&gt; &lt;li&gt;&lt;a href=&quot;#id-introduction&quot;&gt;Introduction&lt;/a&gt; &lt;ol&gt; &lt;li&gt;&lt;a href=&quot;#id-why-i-needed-this&quot;&gt;Why I needed this&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-rpc-parameters&quot;&gt;RPC parameters&lt;/a&gt; &lt;ol&gt; &lt;li&gt;&lt;a href=&quot;#id-parameter-traits&quot;&gt;Parameter Traits&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-serialization&quot;&gt;Serialization&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-deserialization&quot;&gt;Deserialization&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-from-tuple-to-function-parameters&quot;&gt;From tuple to function parameters&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-the-rpc-api&quot;&gt;The RPC API&lt;/a&gt; &lt;ol&gt; &lt;li&gt;&lt;a href=&quot;#id-header&quot;&gt;Header&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-table&quot;&gt;Table&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-transport&quot;&gt;Transport&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-result&quot;&gt;Result&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-out-processor&quot;&gt;OutProcessor&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-in-processor&quot;&gt;InProcessor&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-connection&quot;&gt;Connection&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#id-improvements&quot;&gt;Improvements&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;p&gt;&lt;a name=&quot;id-introduction&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h2&gt;Introduction&lt;/h2&gt; &lt;p&gt;&lt;img alt=&quot;&quot; class=&quot;alignnone size-full wp-image-652&quot; src=&quot;http://www.crazygaze.com/blog/wp-content/uploads/2016/06/img_57561179204f5.png&quot; /&gt;&lt;/p&gt; &lt;p&gt;This article explores a C++ RPC framework I&amp;#39;ve been working on which requires no code generation step for glue code. Before I start rambling on implementation details, and so you know what to expect, here is a feature list:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Source available at &lt;a href=&quot;https://bitbucket.org/ruifig/czrpc&quot;&gt;https://bitbucket.org/ruifig/czrpc&lt;/a&gt; &lt;ul&gt; &lt;li&gt;The source code shown in this article is by no means complete. It&amp;#39;s meant to show the foundations upon which the framework was built. Also, to shorten things a bit, it&amp;#39;s a mix of code from the repository at the time of writing and custom sample code, so it might have errors.&lt;/li&gt; &lt;li&gt;Some of the source code which is not directly related to the problem at hand is left intentionally simple with disregard for performance. Any improvements will later be added to source code repository.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Modern C++ (C++11/14) &lt;ul&gt; &lt;li&gt;Requires at least &lt;strong&gt;Visual Studio 2015&lt;/strong&gt;. Clang/GCC is fine too, but might not work as-is, since VS is less strict.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Type-safe &lt;ul&gt; &lt;li&gt;The framework detects at &lt;strong&gt;compile time&lt;/strong&gt; invalid RPC calls, such as unknown RPC names, wrong number of parameters, or wrong parameter types.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Relatively small API and not too verbose (considering it requires no code generation)&lt;/li&gt; &lt;li&gt;Multiple ways to handle RPC replies &lt;ul&gt; &lt;li&gt;Asynchronous handler&lt;/li&gt; &lt;li&gt;Futures&lt;/li&gt; &lt;li&gt;A client can detect if an RPC caused an exception server side&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Allows the use of potentially any type in RPC parameters &lt;ul&gt; &lt;li&gt;Provided the user implements the required functions to deal with that type.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Bidirectional RPCs (A server can call RPCs on a client) &lt;ul&gt; &lt;li&gt;Typically, client code cannot be trusted, but since the framework is to be used between trusted parties, this is not a problem.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Non intrusive &lt;ul&gt; &lt;li&gt;An object being used for RPC calls doesn&amp;#39;t need to know anything about RPCs or network.&lt;/li&gt; &lt;li&gt;This makes it possible to wrap third party classes for RPC calls.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Minimal bandwidth overhead per RPC call&lt;/li&gt; &lt;li&gt;No external dependencies &lt;ul&gt; &lt;li&gt;Although the supplied transport (in the source code repository) uses Asio/Boost Asio, the framework itself does not depend on it. You can plug in your own transport.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;No security features provided &lt;ul&gt; &lt;li&gt;Because the framework is intended to be used between trusted parties (e.g: between servers).&lt;/li&gt; &lt;li&gt;The application can specify its own transport, therefore having a chance to encrypt anything if required.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;p&gt;Even though the source code shown is not complete, the article is still very heavy on code. Code is presented in small portions and every section builds on the previous, but is still an overwhelming amount of code. So that you have an idea of how it will look like in the end, here is a fully functional sample using the source code repository at the time of writing:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;////////////////////////////////////////////////////////////////////////// // Useless RPC-agnostic class that performs calculations. ////////////////////////////////////////////////////////////////////////// class Calculator { public: &nbsp; &nbsp; double add(double a, double b) { return a + b; } }; ////////////////////////////////////////////////////////////////////////// // Define the RPC table for the Calculator class // This needs to be seen by both the server and client code ////////////////////////////////////////////////////////////////////////// #define RPCTABLE_CLASS Calculator #define RPCTABLE_CONTENTS \ &nbsp; &nbsp; REGISTERRPC(add) #include &quot;crazygaze/rpc/RPCGenerate.h&quot; ////////////////////////////////////////////////////////////////////////// // A Server that only accepts 1 client, then shuts down // when the client disconnects ////////////////////////////////////////////////////////////////////////// void RunServer() { &nbsp; &nbsp; asio::io_service io; &nbsp; &nbsp; // Start thread to run Asio's the io_service &nbsp; &nbsp; // we will be using for the server &nbsp; &nbsp; std::thread th = std::thread([&amp;amp;io] { &nbsp; &nbsp; &nbsp; &nbsp; asio::io_service::work w(io); &nbsp; &nbsp; &nbsp; &nbsp; io.run(); &nbsp; &nbsp; }); &nbsp; &nbsp; // Instance we will be using to serve RPC calls. &nbsp; &nbsp; // Note that it's an object that knows nothing about RPCs &nbsp; &nbsp; Calculator calc; &nbsp; &nbsp; // start listening for a client connection. &nbsp; &nbsp; // We specify what Calculator instance clients will use, &nbsp; &nbsp; auto acceptor = AsioTransportAcceptor&amp;lt;Calculator, void&amp;gt;::create(io, calc); &nbsp; &nbsp; // Start listening on port 9000. &nbsp; &nbsp; // For simplicity, we are only expecting 1 client &nbsp; &nbsp; using ConType = Connection&amp;lt;Calculator, void&amp;gt;; &nbsp; &nbsp; std::shared_ptr&amp;lt;ConType&amp;gt; con; &nbsp; &nbsp; acceptor-&amp;gt;start(9000, [&amp;amp;io, &amp;amp;con](std::shared_ptr&amp;lt;ConType&amp;gt; con_) { &nbsp; &nbsp; &nbsp; &nbsp; con = con_; &nbsp; &nbsp; &nbsp; &nbsp; // Since this is just a sample, close the server once the first client &nbsp; &nbsp; &nbsp; &nbsp; // disconnects &nbsp; &nbsp; &nbsp; &nbsp; reinterpret_cast&amp;lt;BaseAsioTransport*&amp;gt;(con-&amp;gt;transport.get()) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; -&amp;gt;setOnClosed([&amp;amp;io] { io.stop(); }); &nbsp; &nbsp; }); &nbsp; &nbsp; th.join(); } ////////////////////////////////////////////////////////////////////////// // A client that connects to the server, calls 1 RPC // then disconnects, causing everything to shut down ////////////////////////////////////////////////////////////////////////// void RunClient() { &nbsp; &nbsp; // Start a thread to run our Asio io_service &nbsp; &nbsp; asio::io_service io; &nbsp; &nbsp; std::thread th = std::thread([&amp;amp;io] { &nbsp; &nbsp; &nbsp; &nbsp; asio::io_service::work w(io); &nbsp; &nbsp; &nbsp; &nbsp; io.run(); &nbsp; &nbsp; }); &nbsp; &nbsp; // Connect to the server (localhost, port 9000) &nbsp; &nbsp; auto con = &nbsp; &nbsp; &nbsp; &nbsp; AsioTransport&amp;lt;void, Calculator&amp;gt;::create(io, &quot;127.0.0.1&quot;, 9000).get(); &nbsp; &nbsp; // Call one RPC (the add method), specifying an asynchronous handler for &nbsp; &nbsp; // when the result arrives &nbsp; &nbsp; CZRPC_CALL(*con, add, 1, 2) &nbsp; &nbsp; &nbsp; &nbsp; .async([&amp;amp;io](Result&amp;lt;double&amp;gt; res) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf(&quot;Result=%f\n&quot;, res.get()); &nbsp;// Prints 3.0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Since this is a just a sample, stop the io_service after we get &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // the result, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // so everything shuts down &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; io.stop(); &nbsp; &nbsp; &nbsp; &nbsp; }); &nbsp; &nbsp; th.join(); } // For testing simplicity, run both the server and client on the same machine, void RunServerAndClient() { &nbsp; &nbsp; auto a = std::thread([] { RunServer(); }); &nbsp; &nbsp; auto b = std::thread([] { RunClient(); }); &nbsp; &nbsp; a.join(); &nbsp; &nbsp; b.join(); }&lt;/code&gt;&lt;/pre&gt; &lt;p&gt;This code is mostly setup code, since the provided transport uses Asio. The RPC calls itself can be as simple as:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;// RPC call using asynchronous handler to handle the result CZRPC_CALL(*con, add, 1, 2).async([](Result&amp;lt;double&amp;gt; res) { &nbsp; &nbsp; printf(&quot;Result=%f\n&quot;, res.get()); &nbsp;// Prints 3.0 }); // RPC call using std::future to handle the result Result&amp;lt;double&amp;gt; res = CZRPC_CALL(*con, add, 1, 2).ft().get(); printf(&quot;Result=%f\n&quot;, res.get()); &nbsp;// Prints 3.0&lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;a name=&quot;id-why-i-needed-this&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Why I needed this&lt;/h3&gt; &lt;p&gt;The game I&amp;#39;ve been working on for a couple of years now (&lt;a href=&quot;https://bitbucket.org/ruifig/g4devkit&quot;&gt;code named G4&lt;/a&gt;), gives players fully simulated little in-game computers they can code for whatever they want. That requires me to have a couple of server types running:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Gameplay Server(s)&lt;/li&gt; &lt;li&gt;VM Server(s) (Simulates the in-game computers) &lt;ul&gt; &lt;li&gt;So that in-game computers can be simulated even if the player is not currently online&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;VM Disk Server(s) &lt;ul&gt; &lt;li&gt;Deals with in-game computer&amp;#39;s storage, like floppies or hard drives.&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;Database server(s)&lt;/li&gt; &lt;li&gt;Login server(s)&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;All these servers need to exchange data, therefore the need for a flexible RPC framework.&lt;/p&gt; &lt;p&gt;Initially I had a custom solution where I would tag methods of a class with certain attributes, then have a Clang based parser (&lt;a href=&quot;https://github.com/Celtoys/clReflect&quot;&gt;clReflect&lt;/a&gt;) generate any required serialization and glue code.&lt;/p&gt; &lt;p&gt;Although it worked fine for the most part, for the past year or so I kept wondering how could I use the new C++11/14 features to create a minimal type safe C++ RPC framework. Something that would not need a code generation step for glue code, while still keeping an acceptable API.&lt;/p&gt; &lt;p&gt;For serialization of non-fundamental types, code generation is still useful, so I don&amp;#39;t need to manually define how to serialize all the fields of a given struct/class. Although defining those manually is not a big deal, I believe.&lt;/p&gt; &lt;p&gt;&lt;a name=&quot;id-rpc-parameters&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h2&gt;RPC Parameters&lt;/h2&gt; &lt;p&gt;Given a function, in order to have type safe RPC calls, there are a few things we need to be able to do:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Identify at compile time if this function is a valid RPC function (Right number of parameters, right type of parameters, etc)&lt;/li&gt; &lt;li&gt;Check if the supplied parameters match (or can be converted) to what the function signature specifies.&lt;/li&gt; &lt;li&gt;Serialize all parameters&lt;/li&gt; &lt;li&gt;Deserialize all parameters&lt;/li&gt; &lt;li&gt;Call the desired function&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;&lt;a name=&quot;id-parameter-traits&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Parameter Traits&lt;/h3&gt; &lt;p&gt;The first problem you&amp;#39;ll face is in deciding what type of parameters are accepted. Some RPC frameworks only accept a limited number of types, such as Thrift. Let&amp;#39;s check the problem.&lt;/p&gt; &lt;p&gt;Given these function signatures:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;void func1(int a, float b, char c); void func2(const char* a, std::string b, const std::string&amp;amp; c); void func3(Foo a, Bar* b); &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;How can we make compile time checks regarding the parameters? Fundamental types are easy enough and should definitely be supported by the framework. A dumb memory copy will do the trick in those cases unless you want to trade a bit of performance for bandwidth usage by cutting down the number of bits needed. But how about complex types such std::string, std::vector, or your own classes? How about pointers, references, const references, rvalues?&lt;/p&gt; &lt;p&gt;We can get some inspiration from what the C++ Standard Library does in the &lt;a href=&quot;http://en.cppreference.com/w/cpp/types&quot;&gt;type_traits&lt;/a&gt; header. We need to be able to query a given type regarding its RPC properties. Let&amp;#39;s put that concept in a template class &lt;code&gt;ParamTraits&amp;lt;T&amp;gt;&lt;/code&gt;, with the following layout .&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;strong&gt;Member constants&lt;/strong&gt;&lt;/th&gt; &lt;th&gt;&amp;nbsp;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;code&gt;valid&lt;/code&gt;&lt;/td&gt; &lt;td&gt;&lt;code&gt;true&lt;/code&gt; if T is valid for RPC parameters, &lt;code&gt;false&lt;/code&gt; otherwise&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Member types&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;code&gt;store_type&lt;/code&gt;&lt;/td&gt; &lt;td&gt;Type used to hold the temporary copy needed when deserializing&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Member functions&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;code&gt;write&lt;/code&gt;&lt;/td&gt; &lt;td&gt;Writes the parameter to a stream&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;code&gt;read&lt;/code&gt;&lt;/td&gt; &lt;td&gt;Reads a parameter into a &lt;code&gt;store_type&lt;/code&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;code&gt;get&lt;/code&gt;&lt;/td&gt; &lt;td&gt;Given a &lt;code&gt;store_type&lt;/code&gt; parameter, it returns what can be passed to the RPC function as a parameter&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;As an example, let&amp;#39;s implement &lt;code&gt;ParamTraits&amp;lt;T&amp;gt;&lt;/code&gt; for arithmetic types, considering we have a stream class with a &lt;code&gt;write&lt;/code&gt; and &lt;code&gt;read&lt;/code&gt; methods:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { // By default, all types for which ParamTraits is not specialized are invalid template &amp;lt;typename T, typename ENABLED = void&amp;gt; struct ParamTraits { &nbsp; &nbsp; using store_type = int; &nbsp; &nbsp; static constexpr bool valid = false; }; // Specialization for arithmetic types template &amp;lt;typename T&amp;gt; struct ParamTraits&amp;lt; &nbsp; &nbsp; T, typename std::enable_if&amp;lt;std::is_arithmetic&amp;lt;T&amp;gt;::value&amp;gt;::type&amp;gt; { &nbsp; &nbsp; using store_type = typename std::decay&amp;lt;T&amp;gt;::type; &nbsp; &nbsp; static constexpr bool valid = true; &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void write(S&amp;amp; s, typename std::decay&amp;lt;T&amp;gt;::type v) { &nbsp; &nbsp; &nbsp; &nbsp; s.write(&amp;amp;v, sizeof(v)); &nbsp; &nbsp; } &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void read(S&amp;amp; s, store_type&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; s.read(&amp;amp;v, sizeof(v)); &nbsp; &nbsp; } &nbsp; &nbsp; static store_type get(store_type v) { &nbsp; &nbsp; &nbsp; &nbsp; return v; &nbsp; &nbsp; } }; } &nbsp;// namespace rpc } &nbsp;// namespace cz &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;And a simple test:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;#define TEST(exp) printf(&quot;%s = %s\n&quot;, #exp, exp ? &quot;true&quot; : &quot;false&quot;); void testArithmetic() { &nbsp; &nbsp; TEST(ParamTraits&amp;lt;int&amp;gt;::valid); &nbsp; &nbsp; &nbsp; &nbsp; // true &nbsp; &nbsp; TEST(ParamTraits&amp;lt;const int&amp;gt;::valid); &nbsp; // true &nbsp; &nbsp; TEST(ParamTraits&amp;lt;int&amp;amp;&amp;gt;::valid); &nbsp; &nbsp; &nbsp; &nbsp;// false &nbsp; &nbsp; TEST(ParamTraits&amp;lt;const int&amp;amp;&amp;gt;::valid); &nbsp;// false } &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;code&gt;ParamTraits&amp;lt;T&amp;gt;&lt;/code&gt; is also used to check if return types are valid, and since a void function is valid, we need to specialize &lt;code&gt;ParamTraits&lt;/code&gt; for void too.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { // void type is valid template &amp;lt;&amp;gt; struct ParamTraits&amp;lt;void&amp;gt; { &nbsp; &nbsp; static constexpr bool valid = true; &nbsp; &nbsp; using store_type = void; }; } &nbsp;// namespace rpc } &nbsp;// namespace cz &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;The apparently strange thing with the specialization for &lt;code&gt;void&lt;/code&gt; is that it also specifies a &lt;code&gt;store_type&lt;/code&gt;. We can&amp;#39;t use it to store anything, but will make some of the later template code easier.&lt;/p&gt; &lt;p&gt;With these &lt;code&gt;ParamTraits&lt;/code&gt; examples, references are not valid RPC parameters. In practice you do want to allow const references at least, especially for fundamental types. A tweak can be added to enable support for &lt;code&gt;const T&amp;amp;&lt;/code&gt; for any valid T if your application needs it.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;// Make &quot;const T&amp;amp;&quot; valid for any valid T #define CZRPC_ALLOW_CONST_LVALUE_REFS &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\ &nbsp; &nbsp; namespace cz { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \ &nbsp; &nbsp; namespace rpc { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\ &nbsp; &nbsp; template &amp;lt;typename T&amp;gt; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\ &nbsp; &nbsp; struct ParamTraits&amp;lt;const T&amp;amp;&amp;gt; : ParamTraits&amp;lt;T&amp;gt; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\ &nbsp; &nbsp; &nbsp; &nbsp; static_assert(ParamTraits&amp;lt;T&amp;gt;::valid, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;Invalid RPC parameter type. Specialize ParamTraits if &quot; \ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;required.&quot;); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\ &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \ &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\ &nbsp; &nbsp; } &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;Similar tweaks can be made to enable support for &lt;code&gt;T&amp;amp;&lt;/code&gt; or &lt;code&gt;T&amp;amp;&amp;amp;&lt;/code&gt; if required, although if the function makes changes to those parameters, those changes will be lost.&lt;/p&gt; &lt;p&gt;Let&amp;#39;s try adding support for a complex type, such as &lt;code&gt;std::vector&amp;lt;T&amp;gt;&lt;/code&gt;. For &lt;code&gt;std::vector&amp;lt;T&amp;gt;&lt;/code&gt; to be supported, &lt;code&gt;T&lt;/code&gt; needs to be supported too.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { template &amp;lt;typename T&amp;gt; struct ParamTraits&amp;lt;std::vector&amp;lt;T&amp;gt;&amp;gt; { &nbsp; &nbsp; using store_type = std::vector&amp;lt;T&amp;gt;; &nbsp; &nbsp; static constexpr bool valid = ParamTraits&amp;lt;T&amp;gt;::valid; &nbsp; &nbsp; static_assert(ParamTraits&amp;lt;T&amp;gt;::valid == true, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;T is not valid RPC parameter type.&quot;); &nbsp; &nbsp; // std::vector serialization is done by writing the vector size, followed by &nbsp; &nbsp; // each element &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void write(S&amp;amp; s, const std::vector&amp;lt;T&amp;gt;&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; int len = static_cast&amp;lt;int&amp;gt;(v.size()); &nbsp; &nbsp; &nbsp; &nbsp; s.write(&amp;amp;len, sizeof(len)); &nbsp; &nbsp; &nbsp; &nbsp; for (auto&amp;amp;&amp;amp; i : v) ParamTraits&amp;lt;T&amp;gt;::write(s, i); &nbsp; &nbsp; } &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void read(S&amp;amp; s, std::vector&amp;lt;T&amp;gt;&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; int len; &nbsp; &nbsp; &nbsp; &nbsp; s.read(&amp;amp;len, sizeof(len)); &nbsp; &nbsp; &nbsp; &nbsp; v.clear(); &nbsp; &nbsp; &nbsp; &nbsp; while (len--) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; T i; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ParamTraits&amp;lt;T&amp;gt;::read(s, i); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.push_back(std::move(i)); &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; } &nbsp; &nbsp; static std::vector&amp;lt;T&amp;gt;&amp;amp;&amp;amp; get(std::vector&amp;lt;T&amp;gt;&amp;amp;&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; return std::move(v); &nbsp; &nbsp; } }; } &nbsp;// namespace rpc } &nbsp;// namespace cz // A simple test void testVector() { &nbsp; &nbsp; TEST(ParamTraits&amp;lt;std::vector&amp;lt;int&amp;gt;&amp;gt;::valid); &nbsp;// true &nbsp; &nbsp; // true if support for const refs was enabled &nbsp; &nbsp; TEST(ParamTraits&amp;lt;const std::vector&amp;lt;int&amp;gt;&amp;amp;&amp;gt;::valid); }&lt;/code&gt;&lt;/pre&gt; &lt;p&gt;For convenience, we can use the &lt;code&gt;&amp;lt;&amp;lt;&lt;/code&gt; and &lt;code&gt;&amp;gt;&amp;gt;&lt;/code&gt; operators with &lt;code&gt;Stream&lt;/code&gt; class (not shown here). Those operators simply call the respective &lt;code&gt;ParamTraits&amp;lt;T&amp;gt;&lt;/code&gt; &lt;code&gt;read&lt;/code&gt; and &lt;code&gt;write&lt;/code&gt; functions.&lt;/p&gt; &lt;p&gt;Now that we can check if a specific type is allowed for RPC parameters, we can build on that and check if a function can be used for RPCs. This is implemented with variadic templates.&lt;/p&gt; &lt;p&gt;First let&amp;#39;s create a template to tells us if a bunch of parameters are valid.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { // // Validate if all parameter types in a parameter pack can be used for RPC // calls // template &amp;lt;typename... T&amp;gt; struct ParamPack { &nbsp; &nbsp; static constexpr bool valid = true; }; template &amp;lt;typename First&amp;gt; struct ParamPack&amp;lt;First&amp;gt; { &nbsp; &nbsp; static constexpr bool valid = ParamTraits&amp;lt;First&amp;gt;::valid; }; template &amp;lt;typename First, typename... Rest&amp;gt; struct ParamPack&amp;lt;First, Rest...&amp;gt; { &nbsp; &nbsp; static constexpr bool valid = &nbsp; &nbsp; &nbsp; &nbsp; ParamTraits&amp;lt;First&amp;gt;::valid &amp;amp;&amp;amp; ParamPack&amp;lt;Rest...&amp;gt;::valid; } } &nbsp;// namespace rpc } &nbsp;// namespace cz // Usage example: void testParamPack() { &nbsp; &nbsp; TEST(ParamPack&amp;lt;&amp;gt;::valid); &nbsp;// true (No parameters is a valid too) &nbsp; &nbsp; TEST((ParamPack&amp;lt;int, double&amp;gt;::valid)); &nbsp;// true &nbsp; &nbsp; TEST((ParamPack&amp;lt;int, int*&amp;gt;::valid)); &nbsp; &nbsp;// false }&lt;/code&gt;&lt;/pre&gt; &lt;p&gt;Using &lt;code&gt;ParamPack&lt;/code&gt;, we can now create a &lt;code&gt;FunctionTraits&lt;/code&gt; template to query a function&amp;#39;s properties.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { template &amp;lt;class F&amp;gt; struct FunctionTraits {}; // For free function pointers template &amp;lt;class R, class... Args&amp;gt; struct FunctionTraits&amp;lt;R (*)(Args...)&amp;gt; : public FunctionTraits&amp;lt;R(Args...)&amp;gt; {}; // For method pointers template &amp;lt;class R, class C, class... Args&amp;gt; struct FunctionTraits&amp;lt;R (C::*)(Args...)&amp;gt; : public FunctionTraits&amp;lt;R(Args...)&amp;gt; { &nbsp; &nbsp; using class_type = C; }; // For const method pointers template &amp;lt;class R, class C, class... Args&amp;gt; struct FunctionTraits&amp;lt;R (C::*)(Args...) const&amp;gt; &nbsp; &nbsp; : public FunctionTraits&amp;lt;R(Args...)&amp;gt; { &nbsp; &nbsp; using class_type = C; }; template &amp;lt;class R, class... Args&amp;gt; struct FunctionTraits&amp;lt;R(Args...)&amp;gt; { &nbsp; &nbsp; // Tells if both the return type and parameters are valid for RPC calls &nbsp; &nbsp; static constexpr bool valid = &nbsp; &nbsp; &nbsp; &nbsp; ParamTraits&amp;lt;R&amp;gt;::valid &amp;amp;&amp;amp; ParamPack&amp;lt;Args...&amp;gt;::valid; &nbsp; &nbsp; using return_type = R; &nbsp; &nbsp; // Number of parameters &nbsp; &nbsp; static constexpr std::size_t arity = sizeof...(Args); &nbsp; &nbsp; // A tuple that can store all parameters &nbsp; &nbsp; using param_tuple = std::tuple&amp;lt;typename ParamTraits&amp;lt;Args&amp;gt;::store_type...&amp;gt;; &nbsp; &nbsp; // Allows us to get the type of each parameter, given an index &nbsp; &nbsp; template &amp;lt;std::size_t N&amp;gt; &nbsp; &nbsp; struct argument { &nbsp; &nbsp; &nbsp; &nbsp; static_assert(N &amp;lt; arity, &quot;error: invalid parameter index.&quot;); &nbsp; &nbsp; &nbsp; &nbsp; using type = typename std::tuple_element&amp;lt;N, std::tuple&amp;lt;Args...&amp;gt;&amp;gt;::type; &nbsp; &nbsp; }; }; } &nbsp;// namespace rpc } &nbsp;// namespace cz // A simple test... struct FuncTraitsTest { &nbsp; &nbsp; void func1() const {} &nbsp; &nbsp; void func2(int) {} &nbsp; &nbsp; int func3(const std::vector&amp;lt;int&amp;gt;&amp;amp;) { return 0; } &nbsp; &nbsp; int* func4() { return 0; } }; void testFunctionTraits() { &nbsp; &nbsp; TEST(FunctionTraits&amp;lt;decltype(&amp;amp;FuncTraitsTest::func1)&amp;gt;::valid); &nbsp;// true &nbsp; &nbsp; TEST(FunctionTraits&amp;lt;decltype(&amp;amp;FuncTraitsTest::func2)&amp;gt;::valid); &nbsp;// true &nbsp; &nbsp; TEST(FunctionTraits&amp;lt;decltype(&amp;amp;FuncTraitsTest::func3)&amp;gt;::valid); &nbsp;// true &nbsp; &nbsp; TEST(FunctionTraits&amp;lt;decltype(&amp;amp;FuncTraitsTest::func4)&amp;gt;::valid); &nbsp;// false }&lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;code&gt;FunctionTraits&lt;/code&gt; gives us a couple of properties that will be used later. Note for example that &lt;code&gt;FunctionTraits::param_tuple&lt;/code&gt; builds on &lt;code&gt;ParamTraits&amp;lt;T&amp;gt;::store_type&lt;/code&gt; . This is needed, since at some point we need a way to deserialize all parameters into a tuple before calling the function.&lt;/p&gt; &lt;p&gt;&lt;a name=&quot;id-serialization&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Serialization&lt;/h3&gt; &lt;p&gt;Since we now have the required code for querying parameters, return types and validating functions, we can put together the code to serialize a function call. Also, it is type safe. It will not compile if given the wrong number or type of parameters, or if the function itself is not valid for RPCs (e.g: unsupported return/parameter types).&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { namespace details { template &amp;lt;typename F, int N&amp;gt; struct Parameters { &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void serialize(S&amp;amp;) {} &nbsp; &nbsp; template &amp;lt;typename S, typename First, typename... Rest&amp;gt; &nbsp; &nbsp; static void serialize(S&amp;amp; s, First&amp;amp;&amp;amp; first, Rest&amp;amp;&amp;amp;... rest) { &nbsp; &nbsp; &nbsp; &nbsp; using Traits = &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ParamTraits&amp;lt;typename FunctionTraits&amp;lt;F&amp;gt;::template argument&amp;lt;N&amp;gt;::type&amp;gt;; &nbsp; &nbsp; &nbsp; &nbsp; Traits::write(s, std::forward&amp;lt;First&amp;gt;(first)); &nbsp; &nbsp; &nbsp; &nbsp; Parameters&amp;lt;F, N + 1&amp;gt;::serialize(s, std::forward&amp;lt;Rest&amp;gt;(rest)...); &nbsp; &nbsp; } }; } &nbsp;// namespace details template &amp;lt;typename F, typename... Args&amp;gt; void serializeMethod(Stream&amp;amp; s, Args&amp;amp;&amp;amp;... args) { &nbsp; &nbsp; using Traits = FunctionTraits&amp;lt;F&amp;gt;; &nbsp; &nbsp; static_assert(Traits::valid, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;Function signature not valid for RPC calls. Check if &quot; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;parameter types are valid&quot;); &nbsp; &nbsp; static_assert(Traits::arity == sizeof...(Args), &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;Invalid number of parameters for RPC call.&quot;); &nbsp; &nbsp; details::Parameters&amp;lt;F, 0&amp;gt;::serialize(s, std::forward&amp;lt;Args&amp;gt;(args)...); } } &nbsp;// namespace rpc } &nbsp;// namespace cz // // A simple test //&nbsp; struct SerializeTest { &nbsp; &nbsp; void func1(int, const std::vector&amp;lt;int&amp;gt;) {} &nbsp; &nbsp; void func2(int*) {} }; void testSerializeCall() { &nbsp; &nbsp; Stream s; &nbsp; &nbsp; serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;(s, 1, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;std::vector&amp;lt;int&amp;gt;{1, 2, 3}); &nbsp; &nbsp; // These fail to compile because of the wrong number of parameters &nbsp; &nbsp; // serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;(s); &nbsp; &nbsp; // serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;(s, 1); &nbsp; &nbsp; // Doesn't compile because of wrong type of parameters &nbsp; &nbsp; // serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;(s, 1, 2); &nbsp; &nbsp; // Doesn't compile because the function can't be used for RPCs. &nbsp; &nbsp; // int a; &nbsp; &nbsp; // serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func2)&amp;gt;(s, &amp;amp;a); } &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;a name=&quot;id-deserialization&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Deserialization&lt;/h3&gt; &lt;p&gt;As mentioned above, &lt;code&gt;FunctionTraits&amp;lt;F&amp;gt;::param_tuple&lt;/code&gt; is the &lt;code&gt;std::tuple&lt;/code&gt; type we can use to hold all the function&amp;#39;s parameters. In order to be able to use this tuple to deserialize parameters, we need to specialize &lt;code&gt;ParamTraits&lt;/code&gt; for tuples. This has the nice side effect of also making it possible to use &lt;code&gt;std::tuple&lt;/code&gt; for RPC parameters.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { namespace details { template &amp;lt;typename T, bool Done, int N&amp;gt; struct Tuple { &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void deserialize(S&amp;amp; s, T&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; s &amp;gt;&amp;gt; std::get&amp;lt;N&amp;gt;(v); &nbsp; &nbsp; &nbsp; &nbsp; Tuple&amp;lt;T, N == std::tuple_size&amp;lt;T&amp;gt;::value - 1, N + 1&amp;gt;::deserialize(s, v); &nbsp; &nbsp; } &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void serialize(S&amp;amp; s, const T&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; s &amp;lt;&amp;lt; std::get&amp;lt;N&amp;gt;(v); &nbsp; &nbsp; &nbsp; &nbsp; Tuple&amp;lt;T, N == std::tuple_size&amp;lt;T&amp;gt;::value - 1, N + 1&amp;gt;::serialize(s, v); &nbsp; &nbsp; } }; template &amp;lt;typename T, int N&amp;gt; struct Tuple&amp;lt;T, true, N&amp;gt; { &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void deserialize(S&amp;amp;, T&amp;amp;) {} &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void serialize(S&amp;amp;, const T&amp;amp;) {} }; } &nbsp;// namespace details template &amp;lt;typename... T&amp;gt; struct ParamTraits&amp;lt;std::tuple&amp;lt;T...&amp;gt;&amp;gt; { &nbsp; &nbsp; using tuple_type = std::tuple&amp;lt;T...&amp;gt;; &nbsp;// for internal use &nbsp; &nbsp; using store_type = tuple_type; &nbsp; &nbsp; static constexpr bool valid = ParamPack&amp;lt;T...&amp;gt;::valid; &nbsp; &nbsp; static_assert( &nbsp; &nbsp; &nbsp; &nbsp; ParamPack&amp;lt;T...&amp;gt;::valid == true, &nbsp; &nbsp; &nbsp; &nbsp; &quot;One or more tuple elements is not a valid RPC parameter type.&quot;); &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void write(S&amp;amp; s, const tuple_type&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; details::Tuple&amp;lt;tuple_type, std::tuple_size&amp;lt;tuple_type&amp;gt;::value == 0, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&amp;gt;::serialize(s, v); &nbsp; &nbsp; } &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static void read(S&amp;amp; s, tuple_type&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; details::Tuple&amp;lt;tuple_type, std::tuple_size&amp;lt;tuple_type&amp;gt;::value == 0, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&amp;gt;::deserialize(s, v); &nbsp; &nbsp; } &nbsp; &nbsp; static tuple_type&amp;amp;&amp;amp; get(tuple_type&amp;amp;&amp;amp; v) { &nbsp; &nbsp; &nbsp; &nbsp; return std::move(v); &nbsp; &nbsp; } }; } &nbsp;// namespace rpc } &nbsp;// namespace cz // A simple test void testDeserialization() { &nbsp; &nbsp; Stream s; &nbsp; &nbsp; serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;(s, 1, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;std::vector&amp;lt;int&amp;gt;{1, 2}); &nbsp; &nbsp; // deserialize the parameters into a tuple. &nbsp; &nbsp; // the tuple is of type std::tuple&amp;lt;int,std::vector&amp;lt;int&amp;gt;&amp;gt; &nbsp; &nbsp; FunctionTraits&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;::param_tuple params; &nbsp; &nbsp; s &amp;gt;&amp;gt; params; }; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;a name=&quot;id-from-tuple-to-function-parameters&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;From tuple to function parameters&lt;/h3&gt; &lt;p&gt;After we deserialize all the parameters into a tuple, we now need to figure out how to unpack the tuple to call a matching function. This is once again done with variadic templates.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { namespace detail { template &amp;lt;typename F, typename Tuple, bool Done, int Total, int... N&amp;gt; struct callmethod_impl { &nbsp; &nbsp; static decltype(auto) call(typename FunctionTraits&amp;lt;F&amp;gt;::class_type&amp;amp; obj, F f, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Tuple&amp;amp;&amp;amp; t) { &nbsp; &nbsp; &nbsp; &nbsp; return callmethod_impl&amp;lt;F, Tuple, Total == 1 + sizeof...(N), Total, N..., &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sizeof...(N)&amp;gt;::call(obj, f, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;std::forward&amp;lt;Tuple&amp;gt;(t)); &nbsp; &nbsp; } }; template &amp;lt;typename F, typename Tuple, int Total, int... N&amp;gt; struct callmethod_impl&amp;lt;F, Tuple, true, Total, N...&amp;gt; { &nbsp; &nbsp; static decltype(auto) call(typename FunctionTraits&amp;lt;F&amp;gt;::class_type&amp;amp; obj, F f, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Tuple&amp;amp;&amp;amp; t) { &nbsp; &nbsp; &nbsp; &nbsp; using Traits = FunctionTraits&amp;lt;F&amp;gt;; &nbsp; &nbsp; &nbsp; &nbsp; return (obj.*f)( &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ParamTraits&amp;lt;typename Traits::template argument&amp;lt;N&amp;gt;::type&amp;gt;::get( &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::get&amp;lt;N&amp;gt;(std::forward&amp;lt;Tuple&amp;gt;(t)))...); &nbsp; &nbsp; } }; } &nbsp;// namespace details template &amp;lt;typename F, typename Tuple&amp;gt; decltype(auto) callMethod(typename FunctionTraits&amp;lt;F&amp;gt;::class_type&amp;amp; obj, F f, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Tuple&amp;amp;&amp;amp; t) { &nbsp; &nbsp; static_assert(FunctionTraits&amp;lt;F&amp;gt;::valid, &quot;Function not usable as RPC&quot;); &nbsp; &nbsp; typedef typename std::decay&amp;lt;Tuple&amp;gt;::type ttype; &nbsp; &nbsp; return detail::callmethod_impl&amp;lt; &nbsp; &nbsp; &nbsp; &nbsp; F, Tuple, 0 == std::tuple_size&amp;lt;ttype&amp;gt;::value, &nbsp; &nbsp; &nbsp; &nbsp; std::tuple_size&amp;lt;ttype&amp;gt;::value&amp;gt;::call(obj, f, std::forward&amp;lt;Tuple&amp;gt;(t)); } } &nbsp;// namespace rpc } &nbsp;// namespace cz // A simple test void testCall() { &nbsp; &nbsp; Stream s; &nbsp; &nbsp; // serialize &nbsp; &nbsp; serializeMethod&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;(s, 1, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;std::vector&amp;lt;int&amp;gt;{1, 2}); &nbsp; &nbsp; // deserialize &nbsp; &nbsp; FunctionTraits&amp;lt;decltype(&amp;amp;SerializeTest::func1)&amp;gt;::param_tuple params; &nbsp; &nbsp; s &amp;gt;&amp;gt; params; &nbsp; &nbsp; // Call func1 on an object, unpacking the tuple into parameters &nbsp; &nbsp; SerializeTest obj; &nbsp; &nbsp; callMethod(obj, &amp;amp;SerializeTest::func1, std::move(params)); }; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;So, we now know how to validate a function, serialize, deserialize, and call it. That&amp;#39;s the low level code done. The layer we&amp;#39;ll now build on top of this code will be the actual RPC API.&lt;/p&gt; &lt;p&gt;&lt;a name=&quot;id-the-rpc-api&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h2&gt;The RPC API&lt;/h2&gt; &lt;p&gt;&lt;a name=&quot;id-header&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Header&lt;/h3&gt; &lt;p&gt;The header contains the following information:&lt;/p&gt; &lt;p&gt;&lt;img alt=&quot;&quot; class=&quot;alignnone size-full wp-image-575&quot; src=&quot;http://www.crazygaze.com/blog/wp-content/uploads/2016/05/img_574cbb33e8851.png&quot; /&gt;&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Field&lt;/th&gt; &lt;th&gt;&amp;nbsp;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;size&lt;/td&gt; &lt;td&gt;Total size in bytes of the RPC. Having the size as part of the header greatly simplifies things, since we can check if we received all the data before trying to process the RPC.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;counter&lt;/td&gt; &lt;td&gt;Call number. Every time we call an RPC, a counter is incremented and assigned to that RPC call.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;rpcid&lt;/td&gt; &lt;td&gt;The function to call&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;isReply&lt;/td&gt; &lt;td&gt;If true, it&amp;#39;s a reply to an RPC. If false, it&amp;#39;s an RPC call.&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;success&lt;/td&gt; &lt;td&gt;This only applies to replies (isReply==true). If true, the call was successful and the data is the reply. If false, the data is the exception information&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;The counter and rpcid form a key that identifies an RPC call instance. This is needed to match an incoming RPC reply to the RPC call that caused it.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { // Small utility struct to make it easier to work with the RPC headers struct Header { &nbsp; &nbsp; enum { &nbsp; &nbsp; &nbsp; &nbsp; kSizeBits = 32, &nbsp; &nbsp; &nbsp; &nbsp; kRPCIdBits = 8, &nbsp; &nbsp; &nbsp; &nbsp; kCounterBits = 22, &nbsp; &nbsp; }; &nbsp; &nbsp; explicit Header() { &nbsp; &nbsp; &nbsp; &nbsp; static_assert(sizeof(*this) == sizeof(uint64_t), &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;Invalid size. Check the bitfields&quot;); &nbsp; &nbsp; &nbsp; &nbsp; all_ = 0; &nbsp; &nbsp; } &nbsp; &nbsp; struct Bits { &nbsp; &nbsp; &nbsp; &nbsp; uint32_t size : kSizeBits; &nbsp; &nbsp; &nbsp; &nbsp; unsigned counter : kCounterBits; &nbsp; &nbsp; &nbsp; &nbsp; unsigned rpcid : kRPCIdBits; &nbsp; &nbsp; &nbsp; &nbsp; unsigned isReply : 1; &nbsp;// Is it a reply to a RPC call ? &nbsp; &nbsp; &nbsp; &nbsp; unsigned success : 1; &nbsp;// Was the RPC call a success ? &nbsp; &nbsp; }; &nbsp; &nbsp; uint32_t key() const { &nbsp; &nbsp; &nbsp; &nbsp; return (bits.counter &amp;lt;&amp;lt; kRPCIdBits) | bits.rpcid; &nbsp; &nbsp; } &nbsp; &nbsp; union { &nbsp; &nbsp; &nbsp; &nbsp; Bits bits; &nbsp; &nbsp; &nbsp; &nbsp; uint64_t all_; &nbsp; &nbsp; }; }; inline Stream&amp;amp; operator&amp;lt;&amp;lt;(Stream&amp;amp; s, const Header&amp;amp; v) { &nbsp; &nbsp; s &amp;lt;&amp;lt; v.all_; &nbsp; &nbsp; return s; } inline Stream&amp;amp; operator&amp;gt;&amp;gt;(Stream&amp;amp; s, Header&amp;amp; v) { &nbsp; &nbsp; s &amp;gt;&amp;gt; v.all_; &nbsp; &nbsp; return s; } } &nbsp;// namespace rpc } &nbsp;// namespace cz &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;a name=&quot;id-table&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Table&lt;/h3&gt; &lt;p&gt;We already managed to serialize and deserialize an RPC, but not a way to map a serialized RPC to the right function on the server side. To solve this, we need to assign an ID to each function. The client knows what function it wants to call and fills the header with the right ID. The server checks the header, and knowing the ID, it dispatches to the right handler. Let&amp;#39;s create the basics to define such dispatching tables.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { // // Helper code to dispatch a call. namespace details { // Handle RPCs with return values template &amp;lt;typename R&amp;gt; struct CallHelper { &nbsp; &nbsp; template &amp;lt;typename OBJ, typename F, typename P&amp;gt; &nbsp; &nbsp; static void impl(OBJ&amp;amp; obj, F f, P&amp;amp;&amp;amp; params, Stream&amp;amp; out) { &nbsp; &nbsp; &nbsp; &nbsp; out &amp;lt;&amp;lt; callMethod(obj, f, std::move(params)); &nbsp; &nbsp; } }; // Handle void RPCs template &amp;lt;&amp;gt; struct CallHelper&amp;lt;void&amp;gt; { &nbsp; &nbsp; template &amp;lt;typename OBJ, typename F, typename P&amp;gt; &nbsp; &nbsp; static void impl(OBJ&amp;amp; obj, F f, P&amp;amp;&amp;amp; params, Stream&amp;amp; out) { &nbsp; &nbsp; &nbsp; &nbsp; callMethod(obj, f, std::move(params)); &nbsp; &nbsp; } }; } struct BaseRPCInfo { &nbsp; &nbsp; BaseRPCInfo() {} &nbsp; &nbsp; virtual ~BaseRPCInfo(){}; &nbsp; &nbsp; std::string name; }; class BaseTable { public: &nbsp; &nbsp; BaseTable() {} &nbsp; &nbsp; virtual ~BaseTable() {} &nbsp; &nbsp; bool isValid(uint32_t rpcid) const { &nbsp; &nbsp; &nbsp; &nbsp; return rpcid &amp;lt; m_rpcs.size(); &nbsp; &nbsp; } protected: &nbsp; &nbsp; std::vector&amp;lt;std::unique_ptr&amp;lt;BaseRPCInfo&amp;gt;&amp;gt; m_rpcs; }; template &amp;lt;typename T&amp;gt; class TableImpl : public BaseTable { public: &nbsp; &nbsp; using Type = T; &nbsp; &nbsp; struct RPCInfo : public BaseRPCInfo { &nbsp; &nbsp; &nbsp; &nbsp; std::function&amp;lt;void(Type&amp;amp;, Stream&amp;amp; in, Stream&amp;amp; out)&amp;gt; dispatcher; &nbsp; &nbsp; }; &nbsp; &nbsp; template &amp;lt;typename F&amp;gt; &nbsp; &nbsp; void registerRPC(uint32_t rpcid, const char* name, F f) { &nbsp; &nbsp; &nbsp; &nbsp; assert(rpcid == m_rpcs.size()); &nbsp; &nbsp; &nbsp; &nbsp; auto info = std::make_unique&amp;lt;RPCInfo&amp;gt;(); &nbsp; &nbsp; &nbsp; &nbsp; info-&amp;gt;name = name; &nbsp; &nbsp; &nbsp; &nbsp; info-&amp;gt;dispatcher = [f](Type&amp;amp; obj, Stream&amp;amp; in, Stream&amp;amp; out) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using Traits = FunctionTraits&amp;lt;F&amp;gt;; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typename Traits::param_tuple params; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in &amp;gt;&amp;gt; params; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using R = typename Traits::return_type; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; details::CallHelper&amp;lt;R&amp;gt;::impl(obj, f, std::move(params), out); &nbsp; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; &nbsp; m_rpcs.push_back(std::move(info)); &nbsp; &nbsp; } }; template &amp;lt;typename T&amp;gt; class Table : public TableImpl&amp;lt;T&amp;gt; { &nbsp; &nbsp; static_assert(sizeof(T) == 0, &quot;RPC Table not specified for the type.&quot;); }; } &nbsp;// namespace rpc } &nbsp;// namespace cz &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;The &lt;code&gt;Table&lt;/code&gt; template needs to be specialized for the class we want to use for RPC calls. Say we have a &lt;code&gt;Calculator&lt;/code&gt; class we want to be able to use for RPC calls:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;class Calculator { public: &nbsp; &nbsp; double add(double a, double b) { &nbsp; &nbsp; &nbsp; &nbsp; m_ans = a + b; &nbsp; &nbsp; &nbsp; &nbsp; return m_ans; &nbsp; &nbsp; } &nbsp; &nbsp; double sub(double a, double b) { &nbsp; &nbsp; &nbsp; &nbsp; m_ans = a - b; &nbsp; &nbsp; &nbsp; &nbsp; return m_ans; &nbsp; &nbsp; } &nbsp; &nbsp; double ans() { &nbsp; &nbsp; &nbsp; &nbsp; return m_ans; &nbsp; &nbsp; } private: &nbsp; &nbsp; double m_ans = 0; }; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;We can specialize the &lt;code&gt;Table&lt;/code&gt; template for &lt;code&gt;Calculator&lt;/code&gt;, so both the client and server have something to work with :&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;// Table specialization for Calculator template &amp;lt;&amp;gt; class cz::rpc::Table&amp;lt;Calculator&amp;gt; : cz::rpc::TableImpl&amp;lt;Calculator&amp;gt; { public: &nbsp; &nbsp; enum class RPCId { add, sub, ans }; &nbsp; &nbsp; Table() { &nbsp; &nbsp; &nbsp; &nbsp; registerRPC((int)RPCId::add, &quot;add&quot;, &amp;amp;Calculator::add); &nbsp; &nbsp; &nbsp; &nbsp; registerRPC((int)RPCId::sub, &quot;sub&quot;, &amp;amp;Calculator::sub); &nbsp; &nbsp; &nbsp; &nbsp; registerRPC((int)RPCId::ans, &quot;ans&quot;, &amp;amp;Calculator::ans); &nbsp; &nbsp; } &nbsp; &nbsp; static const RPCInfo* get(uint32_t rpcid) { &nbsp; &nbsp; &nbsp; &nbsp; static Table&amp;lt;Calculator&amp;gt; tbl; &nbsp; &nbsp; &nbsp; &nbsp; assert(tbl.isValid(rpcid)); &nbsp; &nbsp; &nbsp; &nbsp; return static_cast&amp;lt;RPCInfo*&amp;gt;(tbl.m_rpcs[rpcid].get()); &nbsp; &nbsp; } }; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;Given an ID, the &lt;code&gt;get&lt;/code&gt; function returns the dispatcher for the right &lt;code&gt;Calculator&lt;/code&gt; method. We can then pass our &lt;code&gt;Calculator&lt;/code&gt; instance, input and output streams to the dispatcher, which takes care of the rest.&lt;/p&gt; &lt;p&gt;These specializations are quite verbose and error-prone, since the enums and the &lt;code&gt;registerRPC&lt;/code&gt; calls need to match. But we can greatly shorten that with some macros. But first, let&amp;#39;s see a verbose example on how to use this table :&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;void testCalculatorTable() { &nbsp; &nbsp; // Both the client and server need to have access to the necessary table &nbsp; &nbsp; using CalcT = Table&amp;lt;Calculator&amp;gt;; &nbsp; &nbsp; // &nbsp; &nbsp; // Client sends RPC &nbsp; &nbsp; Stream toServer; &nbsp; &nbsp; &nbsp; &nbsp; RPCHeader hdr; &nbsp; &nbsp; hdr.bits.rpcid = (int)CalcT::RPCId::add; &nbsp; &nbsp; toServer &amp;lt;&amp;lt; hdr; &nbsp; &nbsp; serializeMethod&amp;lt;decltype(&amp;amp;Calculator::add)&amp;gt;(toServer, 1.0, 9.0); &nbsp; &nbsp; // &nbsp; &nbsp; // Server receives RPC, and sends back a reply &nbsp; &nbsp; Calculator calc; &nbsp;// object used to receive the RPCs &nbsp; &nbsp; toServer &amp;gt;&amp;gt; hdr; &nbsp; &nbsp; auto&amp;amp;&amp;amp; info = CalcT::get(hdr.bits.rpcid); &nbsp; &nbsp; Stream toClient; &nbsp;// Stream for the reply &nbsp; &nbsp; // Call the desired Calculator function. &nbsp; &nbsp; info-&amp;gt;dispatcher(calc, toServer, toClient); &nbsp; &nbsp; // &nbsp; &nbsp; // Client receives a reply &nbsp; &nbsp; double r; &nbsp; &nbsp; toClient &amp;gt;&amp;gt; r; &nbsp; &nbsp; printf(&quot;%2.0f\n&quot;, r); &nbsp;// Will print &quot;10&quot; } &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;Again, this is quite verbose, but its just to show the code flow. That will be improved later.&lt;/p&gt; &lt;p&gt;Now, how can we simplify the table specializations? If we put the gist of tables specialization in an unguarded header, all you need is a couple of defines followed by an include of that unguarded header to generate what the equivalent of what we did manually.&lt;/p&gt; &lt;p&gt;Example:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;#define RPCTABLE_CLASS Calculator #define RPCTABLE_CONTENTS \ &nbsp; &nbsp; REGISTERRPC(add) \ &nbsp; &nbsp; REGISTERRPC(sub) \ &nbsp; &nbsp; REGISTERRPC(ans) #include &quot;RPCGenerate.h&quot; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;That&amp;#39;s surprisingly simple, no?&lt;/p&gt; &lt;p&gt;The &lt;code&gt;RPCGenerate.h&lt;/code&gt; is an unguarded header that looks like this:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;#ifndef RPCTABLE_CLASS &nbsp; &nbsp; #error &quot;Macro RPCTABLE_CLASS needs to be defined&quot; #endif #ifndef RPCTABLE_CONTENTS &nbsp; &nbsp; #error &quot;Macro RPCTABLE_CONTENTS needs to be defined&quot; #endif #define RPCTABLE_TOOMANYRPCS_STRINGIFY(arg) #arg #define RPCTABLE_TOOMANYRPCS(arg) RPCTABLE_TOOMANYRPCS_STRINGIFY(arg) template&amp;lt;&amp;gt; class cz::rpc::Table&amp;lt;RPCTABLE_CLASS&amp;gt; : cz::rpc::TableImpl&amp;lt;RPCTABLE_CLASS&amp;gt; { public: &nbsp; &nbsp; using Type = RPCTABLE_CLASS; &nbsp; &nbsp; #define REGISTERRPC(rpc) rpc, &nbsp; &nbsp; enum class RPCId { &nbsp; &nbsp; &nbsp; &nbsp; RPCTABLE_CONTENTS &nbsp; &nbsp; &nbsp; &nbsp; NUMRPCS &nbsp; &nbsp; }; &nbsp; &nbsp; Table() &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; static_assert((unsigned)((int)RPCId::NUMRPCS-1)&amp;lt;(1&amp;lt;&amp;lt;Header::kRPCIdBits), &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RPCTABLE_TOOMANYRPCS(Too many RPCs registered for class RPCTABLE_CLASS)); &nbsp; &nbsp; &nbsp; &nbsp; #undef REGISTERRPC &nbsp; &nbsp; &nbsp; &nbsp; #define REGISTERRPC(func) registerRPC((uint32_t)RPCId::func, #func, &amp;amp;Type::func); &nbsp; &nbsp; &nbsp; &nbsp; RPCTABLE_CONTENTS &nbsp; &nbsp; } &nbsp; &nbsp; static const RPCInfo* get(uint32_t rpcid) &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; static Table&amp;lt;RPCTABLE_CLASS&amp;gt; tbl; &nbsp; &nbsp; &nbsp; &nbsp; assert(tbl.isValid(rpcid)); &nbsp; &nbsp; &nbsp; &nbsp; return static_cast&amp;lt;RPCInfo*&amp;gt;(tbl.m_rpcs[rpcid].get()); &nbsp; &nbsp; } }; #undef REGISTERRPC #undef RPCTABLE_START #undef RPCTABLE_END #undef RPCTABLE_CLASS #undef RPCTABLE_CONTENTS #undef RPCTABLE_TOOMANYRPCS_STRINGIFY #undef RPCTABLE_TOOMANYRPCS &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;As a bonus, specializing tables like this makes it easy to support inheritance. Imagine we have a &lt;code&gt;ScientificCalculator&lt;/code&gt; that inherits from Calculator:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;class ScientificCalculator : public Calculator { public: &nbsp; &nbsp; double sqrt(double a) { &nbsp; &nbsp; &nbsp; &nbsp; return std::sqrt(a); &nbsp; &nbsp; } }; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;By separately defining the contents of &lt;code&gt;Calculator&lt;/code&gt;, we can reuse that define:&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;// Separately define the Calculator contents so it can be reused #define RPCTABLE_CALCULATOR_CONTENTS \ &nbsp; &nbsp; REGISTERRPC(add) \ &nbsp; &nbsp; REGISTERRPC(sub) \ &nbsp; &nbsp; REGISTERRPC(ans) // Calculator table #define RPCTABLE_CLASS Calculator #define RPCTABLE_CONTENTS \ &nbsp; &nbsp; RPCTABLE_CALCULATOR_CONTENTS #include &quot;RPCGenerate.h&quot; // ScientificCalculator table #define RPCTABLE_CLASS ScientificCalculator #define RPCTABLE_CONTENTS \ &nbsp; &nbsp; RPCTABLE_CALCULATOR_CONTENTS \ &nbsp; &nbsp; REGISTERRPC(sqrt) #include &quot;RPCGenerate.h&quot; &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;a name=&quot;id-transport&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Transport&lt;/h3&gt; &lt;p&gt;We need to define how data will be transported between client and server. Let&amp;#39;s put that in a &lt;code&gt;Transport&lt;/code&gt; interface class. The interface is intentionally left very simple so the application can specify a custom transport . All we need is a method to send, receive, and to close.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { class Transport { public: &nbsp; &nbsp; virtual ~Transport() {} &nbsp; &nbsp; // Send one single RPC &nbsp; &nbsp; virtual void send(std::vector&amp;lt;char&amp;gt; data) = 0; &nbsp; &nbsp; // Receive one single RPC &nbsp; &nbsp; // dst : Will contain the data for one single RPC, or empty if no RPC &nbsp; &nbsp; // available &nbsp; &nbsp; // return: true if the transport is still alive, false if the transport &nbsp; &nbsp; // closed &nbsp; &nbsp; virtual bool receive(std::vector&amp;lt;char&amp;gt;&amp;amp; dst) = 0; &nbsp; &nbsp; // Close connection to the peer &nbsp; &nbsp; virtual void close() = 0; }; } &nbsp;// namespace rpc } &nbsp;// namespace cz &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;&lt;a name=&quot;id-result&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Result&lt;/h3&gt; &lt;p&gt;How should a RPC result look like? Whenever we make an RPC call, the result can come in 3 forms.&lt;/p&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Form&lt;/th&gt; &lt;th&gt;Meaning&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Valid&lt;/td&gt; &lt;td&gt;We got a reply from the server with the result value of the RPC call&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Aborted&lt;/td&gt; &lt;td&gt;The connection failed or was closed, and therefore we don&amp;#39;t have result value&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Exception&lt;/td&gt; &lt;td&gt;We got a reply from the server with an exception string (The RPC call caused an exception server side)&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { class Exception : public std::exception { public: &nbsp; &nbsp; Exception(const std::string&amp;amp; msg) : std::exception(msg.c_str()) {} }; template &amp;lt;typename T&amp;gt; class Result { public: &nbsp; &nbsp; using Type = T; &nbsp; &nbsp; Result() : m_state(State::Aborted) {} &nbsp; &nbsp; explicit Result(Type&amp;amp;&amp;amp; val) : m_state(State::Valid), m_val(std::move(val)) {} &nbsp; &nbsp; Result(Result&amp;amp;&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; moveFrom(std::move(other)); &nbsp; &nbsp; } &nbsp; &nbsp; Result(const Result&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; copyFrom(other); &nbsp; &nbsp; } &nbsp; &nbsp; ~Result() { &nbsp; &nbsp; &nbsp; &nbsp; destroy(); &nbsp; &nbsp; } &nbsp; &nbsp; Result&amp;amp; operator=(Result&amp;amp;&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; if (this == &amp;amp;other) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return *this; &nbsp; &nbsp; &nbsp; &nbsp; destroy(); &nbsp; &nbsp; &nbsp; &nbsp; moveFrom(std::move(other)); &nbsp; &nbsp; &nbsp; &nbsp; return *this; &nbsp; &nbsp; } &nbsp; &nbsp; // Construction from an exception needs to be separate. so &nbsp; &nbsp; // RPCReply&amp;lt;std::string&amp;gt; works. &nbsp; &nbsp; // Otherwise we would have no way to tell if constructing from a value, or &nbsp; &nbsp; // from an exception &nbsp; &nbsp; static Result fromException(std::string ex) { &nbsp; &nbsp; &nbsp; &nbsp; Result r; &nbsp; &nbsp; &nbsp; &nbsp; r.m_state = State::Exception; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;r.m_ex) std::string(std::move(ex)); &nbsp; &nbsp; &nbsp; &nbsp; return r; &nbsp; &nbsp; } &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static Result fromStream(S&amp;amp; s) { &nbsp; &nbsp; &nbsp; &nbsp; Type v; &nbsp; &nbsp; &nbsp; &nbsp; s &amp;gt;&amp;gt; v; &nbsp; &nbsp; &nbsp; &nbsp; return Result(std::move(v)); &nbsp; &nbsp; }; &nbsp; &nbsp; bool isValid() const { &nbsp; &nbsp; &nbsp; &nbsp; return m_state == State::Valid; &nbsp; &nbsp; } &nbsp; &nbsp; bool isException() const { &nbsp; &nbsp; &nbsp; &nbsp; return m_state == State::Exception; &nbsp; &nbsp; }; &nbsp; &nbsp; bool isAborted() const { &nbsp; &nbsp; &nbsp; &nbsp; return m_state == State::Aborted; &nbsp; &nbsp; } &nbsp; &nbsp; T&amp;amp; get() { &nbsp; &nbsp; &nbsp; &nbsp; if (!isValid()) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw Exception(isException() ? m_ex : &quot;RPC reply was aborted&quot;); &nbsp; &nbsp; &nbsp; &nbsp; return m_val; &nbsp; &nbsp; } &nbsp; &nbsp; const T&amp;amp; get() const { &nbsp; &nbsp; &nbsp; &nbsp; if (!isValid()) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw Exception(isException() ? m_ex : &quot;RPC reply was aborted&quot;); &nbsp; &nbsp; &nbsp; &nbsp; return m_val; &nbsp; &nbsp; } &nbsp; &nbsp; const std::string&amp;amp; getException() { &nbsp; &nbsp; &nbsp; &nbsp; assert(isException()); &nbsp; &nbsp; &nbsp; &nbsp; return m_ex; &nbsp; &nbsp; }; private: &nbsp; &nbsp; void destroy() { &nbsp; &nbsp; &nbsp; &nbsp; if (m_state == State::Valid) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_val.~Type(); &nbsp; &nbsp; &nbsp; &nbsp; else if (m_state == State::Exception) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using String = std::string; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_ex.~String(); &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; m_state = State::Aborted; &nbsp; &nbsp; } &nbsp; &nbsp; void moveFrom(Result&amp;amp;&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; m_state = other.m_state; &nbsp; &nbsp; &nbsp; &nbsp; if (m_state == State::Valid) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;m_val) Type(std::move(other.m_val)); &nbsp; &nbsp; &nbsp; &nbsp; else if (m_state == State::Exception) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;m_ex) std::string(std::move(other.m_ex)); &nbsp; &nbsp; } &nbsp; &nbsp; void copyFrom(const Result&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; m_state = other.m_state; &nbsp; &nbsp; &nbsp; &nbsp; if (m_state == State::Valid) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;m_val) Type(other.m_val); &nbsp; &nbsp; &nbsp; &nbsp; else if (m_state == State::Exception) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;m_ex) std::string(other.m_ex); &nbsp; &nbsp; } &nbsp; &nbsp; enum class State { Valid, Aborted, Exception }; &nbsp; &nbsp; State m_state; &nbsp; &nbsp; union { &nbsp; &nbsp; &nbsp; &nbsp; Type m_val; &nbsp; &nbsp; &nbsp; &nbsp; std::string m_ex; &nbsp; &nbsp; }; }; // void specialization template &amp;lt;&amp;gt; class Result&amp;lt;void&amp;gt; { public: &nbsp; &nbsp; Result() : m_state(State::Aborted) {} &nbsp; &nbsp; Result(Result&amp;amp;&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; moveFrom(std::move(other)); &nbsp; &nbsp; } &nbsp; &nbsp; Result(const Result&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; copyFrom(other); &nbsp; &nbsp; } &nbsp; &nbsp; ~Result() { &nbsp; &nbsp; &nbsp; &nbsp; destroy(); &nbsp; &nbsp; } &nbsp; &nbsp; Result&amp;amp; operator=(Result&amp;amp;&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; if (this == &amp;amp;other) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return *this; &nbsp; &nbsp; &nbsp; &nbsp; destroy(); &nbsp; &nbsp; &nbsp; &nbsp; moveFrom(std::move(other)); &nbsp; &nbsp; &nbsp; &nbsp; return *this; &nbsp; &nbsp; } &nbsp; &nbsp; static Result fromException(std::string ex) { &nbsp; &nbsp; &nbsp; &nbsp; Result r; &nbsp; &nbsp; &nbsp; &nbsp; r.m_state = State::Exception; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;r.m_ex) std::string(std::move(ex)); &nbsp; &nbsp; &nbsp; &nbsp; return r; &nbsp; &nbsp; } &nbsp; &nbsp; template &amp;lt;typename S&amp;gt; &nbsp; &nbsp; static Result fromStream(S&amp;amp; s) { &nbsp; &nbsp; &nbsp; &nbsp; Result r; &nbsp; &nbsp; &nbsp; &nbsp; r.m_state = State::Valid; &nbsp; &nbsp; &nbsp; &nbsp; return r; &nbsp; &nbsp; } &nbsp; &nbsp; bool isValid() const { &nbsp; &nbsp; &nbsp; &nbsp; return m_state == State::Valid; &nbsp; &nbsp; } &nbsp; &nbsp; bool isException() const { &nbsp; &nbsp; &nbsp; &nbsp; return m_state == State::Exception; &nbsp; &nbsp; }; &nbsp; &nbsp; bool isAborted() const { &nbsp; &nbsp; &nbsp; &nbsp; return m_state == State::Aborted; &nbsp; &nbsp; } &nbsp; &nbsp; const std::string&amp;amp; getException() { &nbsp; &nbsp; &nbsp; &nbsp; assert(isException()); &nbsp; &nbsp; &nbsp; &nbsp; return m_ex; &nbsp; &nbsp; }; &nbsp; &nbsp; void get() const { &nbsp; &nbsp; &nbsp; &nbsp; if (!isValid()) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw Exception(isException() ? m_ex : &quot;RPC reply was aborted&quot;); &nbsp; &nbsp; } private: &nbsp; &nbsp; void destroy() { &nbsp; &nbsp; &nbsp; &nbsp; if (m_state == State::Exception) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using String = std::string; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_ex.~String(); &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; m_state = State::Aborted; &nbsp; &nbsp; } &nbsp; &nbsp; void moveFrom(Result&amp;amp;&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; m_state = other.m_state; &nbsp; &nbsp; &nbsp; &nbsp; if (m_state == State::Exception) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;m_ex) std::string(std::move(other.m_ex)); &nbsp; &nbsp; } &nbsp; &nbsp; void copyFrom(const Result&amp;amp; other) { &nbsp; &nbsp; &nbsp; &nbsp; m_state = other.m_state; &nbsp; &nbsp; &nbsp; &nbsp; if (m_state == State::Exception) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new (&amp;amp;m_ex) std::string(other.m_ex); &nbsp; &nbsp; } &nbsp; &nbsp; enum class State { Valid, Aborted, Exception }; &nbsp; &nbsp; State m_state; &nbsp; &nbsp; union { &nbsp; &nbsp; &nbsp; &nbsp; bool m_dummy; &nbsp; &nbsp; &nbsp; &nbsp; std::string m_ex; &nbsp; &nbsp; }; }; } &nbsp;// namespace rpc } &nbsp;// namespace cz &lt;/code&gt;&lt;/pre&gt; &lt;p&gt;The &lt;code&gt;Result&amp;lt;void&amp;gt;&lt;/code&gt; specialization is needed, since for that case there isn&amp;#39;t a result, but the caller still wants to know if the RPC call was properly processed. Initially, I considered using &lt;a href=&quot;https://en.wikipedia.org/wiki/Andrei_Alexandrescu&quot;&gt;&lt;code&gt;Expected&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/a&gt; for RPC replies. But &lt;code&gt;Expected&amp;lt;T&amp;gt;&lt;/code&gt; has basically 2 states (Value or Exception), and we need 3 (Value, Exception, and Aborted). One can think that Aborted could be considered an exception, but from a client point of view, it&amp;#39;s not always the case. In some cases you want to know an RPC failed because the connection was closed, and not because the server replied with an exception.&lt;/p&gt; &lt;p&gt;&lt;a name=&quot;id-out-processor&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;OutProcessor&lt;/h3&gt; &lt;p&gt;We need to track ongoing RPC calls so the user code can get the results when they arrive. Handling a result can be done in two ways. Throught an asynchronous handler (similar to &lt;a href=&quot;https://en.wikipedia.org/wiki/Asio_C%2B%2B_library&quot;&gt;Asio&lt;/a&gt; ), or with a future.&lt;/p&gt; &lt;p&gt;Two classes are needed for this. An outgoing processor and a wrapper for a single RPC call. Another class is needed (&lt;code&gt;Connection&lt;/code&gt;) that ties together outgoing and incoming processors. It will be introduced later.&lt;/p&gt; &lt;pre&gt; &lt;code class=&quot;language-cpp&quot;&gt;namespace cz { namespace rpc { class BaseOutProcessor { public: &nbsp; &nbsp; virtual ~BaseOutProcessor() {} protected: &nbsp; &nbsp; template &amp;lt;typename R&amp;gt; &nbsp; &nbsp; friend class Call; &nbsp; &nbsp; template &amp;lt;typename L, typename R&amp;gt; &nbsp; &nbsp; friend struct Connection; &nbsp; &nbsp; template &amp;lt;typename F, typename H&amp;gt; &nbsp; &nbsp; void commit(Transport&amp;amp; transport, uint32_t rpcid, Stream&amp;amp; data, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; H&amp;amp;&amp;amp; handler) { &nbsp; &nbsp; &nbsp; &nbsp; std::unique_lock&amp;lt;std::mutex&amp;gt; lk(m_mtx); &nbsp; &nbsp; &nbsp; &nbsp; Header hdr; &nbsp; &nbsp; &nbsp; &nbsp; hdr.bits.size = data.writeSize(); &nbsp; &nbsp; &nbsp; &nbsp; hdr.bits.counter = ++m_replyIdCounter; &nbsp; &nbsp; &nbsp; &nbsp; hdr.bits.rpcid = rpcid; &nbsp; &nbsp; &nbsp; &nbsp; *reinterpret_cast&amp;lt;Header*&amp;gt;(data.ptr(0)) = hdr; &nbsp; &nbsp; &nbsp; &nbsp; m_replies[hdr.key()] = [handler = std::move(handler)](Stream * in, &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Header hdr) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; using R = typename ParamTraits&amp;lt; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typename FunctionTraits&amp;lt;F&amp;gt;::return_type&amp;gt;::store_type; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (in) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (hdr.bits.success) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler(Result&amp;lt;R&amp;gt;::fromStream((*in))); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::string str; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (*in) &amp;gt;&amp;gt; str; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler(Result&amp;lt;R&amp;gt;::fromException(std::move(str))); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // if the stream is nullptr, it means the result is being aborted &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler(Result&amp;lt;R&amp;gt;()); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; &nbsp; lk.unlock(); &nbsp; &nbsp; &nbsp; &nbsp; transport.send(data.extract()); &nbsp; &nbsp; } &nbsp; &nbsp; void processReply(Stream&amp;amp; in, Header hdr) { &nbsp; &nbsp; &nbsp; &nbsp; std::function&amp;lt;void(Stream*, Header)&amp;gt; h; &nbsp; &nbsp; &nbsp; &nbsp; { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::unique_lock&amp;lt;std::mutex&amp;gt; lk(m_mtx); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; auto it = m_replies.find(hdr.key()); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; assert(it != m_replies.end()); &nbsp; &nbsp;RPCs on a "Calculator" server     OutProcessor<Calculator> outPrc;     // Handle with an asynchronous handler     outPrc.call<decltype(&Calculator::add)>(               trp, (int)Table<Calculator>::RPCId::add, 1.0, 2.0)         .async([](Result<double> res) {             printf("%2.0f\n", res.get());  // prints '3'         });     // Handle with a future     Result<double> res = outPrc.call<decltype(&Calculator::add)>(                         trp, (int)Table<Calculator>::RPCId::add, 1.0, 3.0)                   .ft().get();     printf("%2.0f\n", res.get());  // prints '4' }

Again, a bit verbose, since I haven't introduced all the code that wraps things up. But shows how the OutProcessor<T> and Call interfaces work. The std::future implementation simply builds on the asynchronous implementation.

InProcessor

Now that we can send an RPC and wait for the result, let's look at what we need to do on the other side. What to do when an RPC call is received on the server.

Let's create a InProcessor<T> class. Contrary to OutProcessor<T>, InProcessor<T> needs to keep a reference to an object of type T. This is so when an RPC is received, it can call the requested method on that object, and send the result back to the client.


namespace cz {
namespace rpc {

class BaseInProcessor {
public:
    virtual ~BaseInProcessor() {}
};

template <typename T>
class InProcessor : public BaseInProcessor {
public:
    using Type = T;
    InProcessor(Type* obj, bool doVoidReplies = true)
        : m_obj(*obj), m_voidReplies(doVoidReplies) {}

    void processCall(Transport& transport, Stream& in, Header hdr) {
        Stream out;
        // Reuse the header as the header for the reply, so we keep the counter
        // and rpcid
        hdr.bits.size = 0;
        hdr.bits.isReply = true;
        hdr.bits.success = true;

        auto&& info = Table<Type>::get(hdr.bits.rpcid);

#if CZRPC_CATCH_EXCEPTIONS
        try {
#endif
            out << hdr;  // Reserve space for the header
            info->dispatcher(m_obj, in, out);
#if CZRPC_CATCH_EXCEPTIONS
        } catch (std::exception& e) {
            out.clear();
            out << hdr;  // Reserve space for the header
            hdr.bits.success = false;
            out << e.what();
        }
#endif

        if (m_voidReplies || (out.writeSize() > sizeof(hdr))) {
            hdr.bits.size = out.writeSize();
            *reinterpret_cast<Header*>(out.ptr(0)) = hdr;
            transport.send(out.extract());
        }
    }

protected:
    Type& m_obj;
    bool m_voidReplies = false;
};

template <>
class InProcessor<void> {
public:
    InProcessor(void*) {}
    void processCall(Transport&, Stream&, Header) {
        assert(0 && "Incoming RPC not allowed for void local type");
    }
};

}  // namespace rpc
}  // namespace cz

The CZRPC_CATCH_EXCEPTIONS define allows us to tweak if we want server side exceptions to be passed to the clients.

It's the use of InProcessor<T> (and Table<T>) that allows calling RPCs on objects that don't know anything about RPCs or network. For example, consider this dummy example:


void calculatorServer() {
    // The object we want to use for RPC calls
    Calculator calc;
    // The server processor. It will call the appropriate methods on 'calc' when
    // an RPC is received
    InProcessor<Calculator> serverProcessor(&calc);
    while (true) {
        // calls to serverProcessor::processCall whenever there is data
    }
}

The Calculator object used for RPCs doesn't know anything about RPCs. The InProcessor<Calculator> does all the required work. This makes it possible use third party classes for RPCs. In some situations, we do want have the class used for RPCs to know about RPCs and/or network. For example, if you're creating a chat system, you have the clients sending messages (RPC calls) to the server. The server needs to know what clients are connected, so it can broadcast messages.

Connection

We can now send and receive RPCs, although with a bit of a verbose API. The OutProcessor<T> and InProcessor<T> template classes deal with what happens to data at both ends of the connection. So, what we need now is exactly that. A Connection to tie in one place everything needed to send and receive data, and simplify the API.


namespace cz {
namespace rpc {

struct BaseConnection {
    virtual ~BaseConnection() {}

    //! Process any incoming RPCs or replies
    // Return true if the connection is still alive, false otherwise
    virtual bool process() = 0;
};

template <typename LOCAL, typename REMOTE>
struct Connection : public BaseConnection {
    using Local = LOCAL;
    using Remote = REMOTE;
    using ThisType = Connection<Local, Remote>;
    Connection(Local* localObj, std::shared_ptr<Transport> transport)
        : localPrc(localObj), transport(std::move(transport)) {}

    template <typename F, typename... Args>
    auto call(Transport& transport, uint32_t rpcid, Args&&... args) {
        return remotePrc.template call<F>(transport, rpcid,
                                          std::forward<Args>(args)...);
    }

    static ThisType* getCurrent() {
        auto it = Callstack<ThisType>::begin();
        return (*it) == nullptr ? nullptr : (*it)->getKey();
    }

    virtual bool process() override {
        // Place a callstack marker, so other code can detect we are serving an
        // RPC
        typename Callstack<ThisType>::Context ctx(this);
        std::vector<char> data;
        while (true) {
            if (!transport->receive(data)) {
                // Transport is closed
                remotePrc.abortReplies();
                return false;
            }

            if (data.size() == 0)
                return true;  // No more pending data to process

            Header hdr;
            Stream in(std::move(data));
            in >> hdr;

            if (hdr.bits.isReply) {
                remotePrc.processReply(in, hdr);
            } else {
                localPrc.processCall(*transport, in, hdr);
            }
        }
    }

    InProcessor<Local> localPrc;
    OutProcessor<Remote> remotePrc;
    std::shared_ptr<Transport> transport;
};

}  // namespace rpc
}  // namespace cz

This puts together the output processor, the input processor, and the transport. To make it possible for user code to detect if it's in the middle of serving an RPC, it uses a class I introduced in an earlier post. The Callstack class. This allows the creation of RPC/network aware code if necessary, like server classes.

So, how this simplifies the API ? Since the Connection<T> has everything we need, one macro taking as parameters the connection object, a function name and the parameters, does everything, including type checks so it doesn't compile if it's an invalid call.


#define CZRPC_CALL(con, func, ...)                                        \
    (con).call<decltype(&std::decay<decltype(con)>::type::Remote::func)>( \
        *(con).transport,                                                 \
        (uint32_t)cz::rpc::Table<                                         \
            std::decay<decltype(con)>::type::Remote>::RPCId::func,        \
        ##__VA_ARGS__)

Using this macro, RPC calls syntax is surprisingly simple. For example, consider this client code:


// Some class to use for RPC calls
class MagicSauce {
public:
    int func1(int a, int b) {
        return a + b;
    }

    int func2(int a, int b) {
        return a + b;
    }
};

// Define RPC table for MagicSauce
#define RPCTABLE_CLASS MagicSauce
#define RPCTABLE_CONTENTS REGISTERRPC(func1)
#include "RPCGenerate.h"

// 'trp' is a fully functional transport
void test_Connection(std::shared_ptr<Transport> trp) {
    Connection<void, MagicSauce> con(nullptr, trp);

    // Doesn't compile : Invalid number of parameters
    // CZRPC_CALL(con, func1, 1);

    // Doesn't compile : Wrong type of parameters
    // CZRPC_CALL(con, func1, 1, "hello");

    // Doesn't compile: func3 is not a MagicSauce method
    // CZRPC_CALL(con, func3, 1, 2);

    // Doesn't compile: func2 is a method of MagicSauce, but not registered as
    // RPC
    // CZRPC_CALL(con, func2, 1, 2);

    // Compiles fine, since everything is valid
    CZRPC_CALL(con, func1, 1, 2).async([](Result<int> res) {
            printf("%d\n", res.get());  // print '3'
        });
}

Notice the void and nullptr used when creating the connection with Connection<void, MagicSauce> con(nullptr, trp); ? This accommodates for bidirectional RPCs (the server can also call RPCs on a client). In this case, we don't expect client side RPCs, so the client side Connection object doesn't have a local object to call RPCs on.

A simplified example (not functional) of bidirectional RPCs can be something like this:


class ChatClient;

class ChatServer {
public:
    // Called by clients to post new messages
    void msg(const char* msg);
    void addNewClient(std::shared_ptr<Transport> trp);

private:
    // Connection specifies both a LOCAL, and REMOTE object types
    std::vector<std::unique_ptr<Connection<ChatServer, ChatClient>>> m_clients;
};

#define RPCTABLE_CLASS ChatServer
#define RPCTABLE_CONTENTS REGISTERRPC(msg)
#include "RPCGenerate.h"

class ChatClient {
public:
    void onMsg(const char* msg);
};

#define RPCTABLE_CLASS ChatClient
#define RPCTABLE_CONTENTS REGISTERRPC(onMsg)
#include "RPCGenerate.h"

void ChatServer::msg(const char* msg) {
    // Simply broadcast the message to all clients
    for (auto&& c : m_clients) {
        CZRPC_CALL(*c, onMsg, msg);
    }
}
void ChatServer::addNewClient(std::shared_ptr<Transport> trp) {
    auto con = std::make_unique<Connection<ChatServer, ChatClient>>(this, trp);
    m_clients.push_back(std::move(con));
}

void ChatClient::onMsg(const char* msg) {
    printf("%s\n", msg);
}

void test_ChatServer() {
    ChatServer server;
    while (true) {
        // Wait for connections, and call ChatServer::addClient
    }
}

// 'trp' is some fully functional transport connected to the ChatServer
void test_ChatClient(std::shared_ptr<Transport> trp) {
    ChatClient client;
    // In this case, we have a client side object to answer RPCs
    Connection<ChatClient, ChatServer> con(&client, trp);
    while (true) {
        // call the 'msg' RPC whenever the user types something, like this:
        CZRPC_CALL(con, msg, "some message");

        // The server will call our client 'onMsg' when other clients send a
        // message
    }
}

The Connection template parameters in the server and client are reversed. Whenever data is received, the Connection object forwards processing to the InProcessor if it's an incoming RPC call (to call on our side), or to the OutProcessor if it's a reply to a previous outgoing RPC call. Data flow for bidirectional RPCs looks like this:

Improvements

A couple of things were left out of the framework intentionally, so the application can decide what's best. For example:

  • Transport initialization

    • The transport interface is very simple, so it doesn't impose any specific way of initialization  or detecting incoming data. It's up to the application to provide a fully functional and connected transport to the Connection class. This is also the reason why I avoided showing any transport initialization, since I would have to present a fully functional transport implementation for that.

    • At the time of writing, the source code repository has one transport implementation using Boost Asio (or standalone Asio)

  • Disconnection detection

    • As with initialization, there is minimal code for dealing with or detecting shutdowns. It is up to the application to decide how to do this with whatever custom transports it provides.

  • At some point I had support for server side functions that return std::futures. But as I was writing this article I removed that to simplify things. That will be added back to the repository soon, since I need it for my own projects.

    • This is needed to support wrapping classes whose API returns std::future instances. Say you have a Login server class with a login method. That login method is in itself probably asynchronous (returns a std::future) since you'll be checking a database for the login details.

    • It's not particularly hard to implement, but it has one niggle I couldn't get rid of without introducing a lot more code. The bulk of the changes would be in the InProcessor<T> class. It would have to keep track of ongoing calls whose std::future<T> instances are not ready yet. The problem here is how would InProcessor<T> detect when those futures are ready so it can send the result back to the client? I can think of two approaches:

      • Regular polling all pending std::futures to see if they are ready.

      • Use continuations (std::future::then), which are not available in the standard yet. That would be the easiest solution. InProcessor<T> would set a continuation to send the result back to the client whenever it is ready. No need for polling anything.

    • This would affect no client side code whatsoever. Say a server side function returns std::future<bool> . All the client sees and needs is still just a Result<bool>.

Read more about:

Featured Blogs

About the Author(s)

Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like