2

Earlier was asking about writing a c wrapper for c++ classes ( C Wrapper for C++ ), which is basically clear.

There's one more question though: how do I deal with c++ templates? Let's say this is my class:

 template<typename T> class Temp
 {
      T get(); 
      void set(T t); 
 }

Is there an elegant way to write a c wrapper?

Community
  • 1
  • 1
Pedro
  • 4,100
  • 10
  • 58
  • 96
  • 1
    If you're not afraid of macros like so many here are, you can wrap it by macros, where `T` is one of the macro arguments. – Shahbaz Oct 08 '11 at 09:33

2 Answers2

5

You have to write a separate wrapper for each specialization.

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
  • is there no way to dynamically handling a new datatype without recompiling the whole project? – Pedro Oct 08 '11 at 03:09
  • 1
    You could use [Boost Preprocessor](http://www.boost.org/doc/libs/1_47_0/libs/preprocessor/doc/index.html) to generate the specializations for you. Define a sequence containing all the types you want to specialize then use SEQ_FOR_EACH to generate the specializations for that sequence. It won't be pretty but it'll work. – Ze Blob Oct 08 '11 at 03:18
  • You could also write a single wrapper that uses `void *` and expect the user to keep track of what he uses it for. – Chris Lutz Oct 08 '11 at 04:00
  • 1
    The C++ compiler automatically generates each specialization that your code needs. The C compiler doesn't know about templates so you have to manually generate each specialization and then provide a C function to call it. So, you figure out what specializations of your template functions you need then you write a C function for each one. – BHS Oct 08 '11 at 04:12
  • 1
    @Chris The `void *` approach works only sometimes. For example, `Temp` and `Temp` will have very different `Get` and `Set` methods. (On the other hand, `Temp` and `Temp` will probably be compatible.) – Raymond Chen Oct 08 '11 at 20:25
0

While it is possible to wrap specific instantiations of a template with C, this is arduous and become infeasible if there are a large number of template instantiations. The more scalable solution would be to write a tool to expand C++ templates in a text-based manner, like a preprocessor. Then, put it in your prebuild step for your compiling script/prefs. Then, you end up with auto-expanded code that could be wrapped with C (or already be magically wrapped into C if the tool were fancy enough). Expanding the template into text shouldn't even be inefficient in runtime, since it is in a way the same thing as what C++ does. But I'd expect it to be a bit slower to compile than a C++ compiler.

VoidStar
  • 5,241
  • 1
  • 31
  • 45