I am dealing with a 3rd party C++ library which makes extensive use of templates. That makes it difficult to create a C API for it to use it from my framework.
Abstracting the problem, suppose the library offers the function:
template <int i> void foo();
template <int i> void zoo(int v);
I want to create a C API with the function head:
extern "C" void c_foo(int i);
extern "C" void c_zoo(int i, int v);
An obvious implementation could be:
void c_foo(int i)
{
switch(i) {
case 1: foo<1>(); break;
case 2: foo<2>(); break;
case 3: foo<3>(); break;
default: break;
};
};
and do the same also for void zoo(int)
.
This works fine if the range of possible values for i
is small. If I want to handle all possible values of i
in [1,100], then it becomes exceedingly ugly to write code in this way, as there is lot of repetition.
Is there any more compact way to do that, i.e. writing less lines of codes? Perhaps using recursive preprocessor macros?