C Wrapper for C++: How to deal with C++ templates?

北城余情 提交于 2019-12-02 05:26:28

问题


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?


回答1:


You have to write a separate wrapper for each specialization.




回答2:


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.



来源:https://stackoverflow.com/questions/7694515/c-wrapper-for-c-how-to-deal-with-c-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!