Question

I have a requirement where I need to generate the function arguments at runtime. At compile time, I do not know the number of arguments or their type. It has to be read from a file at runtime, generate the code and dynamically loaded.

I have used the M4 macro generation language before. It provides great performance at the sacrifice of readability and usability.

I did not want to go that route this time and was thinking of using C++11 Variadic templates.

Is there a better alternative?

Was it helpful?

Solution

Varadic templates won't work because you will need to know at compile-time all possible argument type lists, and then instantiate a template for each one.

Your problem is essentially run-time serialization and de-serialization of types. C++ doesn't have any "in-built" standard way to do this.

You will need to create some GenericParameter type and then have:

`vector<GenericParameter*> params`

or similar. Then for each type you want to encode create a derived class of GenericParameter to box it. When you serialize a set of parameters you need to create and store some sort of type id for each derived class, and then serialize the data for that class. Likewise in the opposite direction you read the type id, construct the appropriate derived class of that type id, and then fill it in with the data for that class.

After you have this you may be able to use varadic templates to verify that a vector of params matches a compiled-in function, and bind the runtime vector to the statically known signature of a function, as well as automatically generate the adapter that takes the generic vector and unboxes the parameters into native types. Likewise in the other direction.

Something to look at is called protobuf, it is heavily used at Google for this sort of thing, and I have heard good things about it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top