In short
I am trying to design a nicer C++ interface for a C library that sends tree-like expressions through a communication channel (à la iostreams vs stdio). I am not sure if it is possible at all to design a DSL within C++ for notating these trees while avoiding runtime overhead, and if yes, how.
Simplified explanation of the C library
There is a C library which can send "expressions" through a communication channel. An "expression" here means a tree structure that can be conveniently notated in a manner similar to function calls.
For example,
f(1, 2, g(3), "foo")
denotes this tree:
Some of you may recognize Mathematica at this point, but I decided to leave that out as it is irrelevant to the question.
We refer to f
as head and 1
, 2
, g(3)
as arguments.
To send this expression, we would write the following:
putHead("f" /* name */, 3 /* argument count */);
putInteger(1);
putInteger(2);
putHead("g" /* name */, 1 /* argument count */);
putInteger(3);
putString("foo");
Question
Is it possible to design a more convenient C++ API for this with the following features?
- More concise to write (think
iostreams
vsstdio
) - Does away with the need to explicitly specify the argument count for each head; instead uses a convenient notation (analogous to
f(1,2,g(3))
from above) from which it infers the argument count automatically - Achieves (2) without runtime overhead (i.e. infer argument count at compile time)
- Must use the above described C interface behind the scenes
I can do (1) with a streams-like interface (i.e. no need to explicitly specify the type of Integer, String, etc. of each argument). I can do (2) in a way that involves extra runtime computation. But I do not know if (2)/(3) together are possible given the features of C++. Ultimately I would like to have a convenient notation for these expressions within C++ itself.
So is it possible to design a DSL within C++ for this while avoiding all runtime overhead? If yes, how? I am not necessarily looking for a full solution with code as the answer, just some pointers to get started, or a summary of an approach that would likely work.