framework
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Tutorial

Table of Contents

A simple example

The code provided in a_simple_example.cpp demonstrates the simplest possible use case for this library - a basic structure is defined, serialized, and deserialized.

#include <fstream>
#include <cassert>
int main ()
{
using ::framework::protocol_buffers::message;
using ::framework::protocol_buffers::required;
using ::framework::protocol_buffers::optional;
using ::framework::protocol_buffers::repeated;
// Define an object type
using object = message <
required <NAME("Field 1"), 1, int32>,
optional <NAME("Field 2"), 2, string_>,
repeated <NAME("Field 3"), 3, int32>>;
// Create an object
object o1 {1, "Hello World!", std::forward_as_tuple(2, 3, 4)};
// Write the object to a file
assert(write(o1, std::ofstream("filename")));
// Read the object from a file
object o2;
assert(read(std::ifstream("filename"), o2));
// Check the result
assert(o1 == o2);
return 0;
}

"filename" output:

0000000: 0801 120c 4865 6c6c 6f20 576f 726c 6421 ....Hello World!
0000010: 1a83 8080 8000 0203 04

Nested serializable types

As the protocol buffer specification allows for strings of arbitrary binary data, nested serializable types may be expressed naturally as demonstrated in nested_types.cpp:

#include <fstream>
#include <cassert>
int main ()
{
using ::framework::protocol_buffers::message;
using ::framework::protocol_buffers::required;
using ::framework::protocol_buffers::optional;
using ::framework::protocol_buffers::repeated;
// Define an object type
using object = message <
required <NAME("Field 1"), 1, int32>,
// Serialized as follows:
// <field length><vector size><int><int>...
required <NAME("Field 2"), 2, stl_vector <int, int>>>;
// Create an object
object o1 {1, std::forward_as_tuple(2, 3, 4)};
// Write the object to a file
assert(write(o1, std::ofstream("filename")));
// Read the object from a file
object o2;
assert(read(std::ifstream("filename"), o2));
// Check the result
assert(o1 == o2);
return 0;
}

"filename" output:

0000000: 0801 1290 8080 8000 0300 0000 0200 0000 ................
0000010: 0300 0000 0400 0000 ........