C Wrapper for C++: How to deal with C++ templates?
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 wrap开发者_开发知识库per?
You have to write a separate wrapper for each specialization.
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.
精彩评论