(1)。在使用C++模板时,编译器(如g++)不会直接编译模板定义(只能在头文件中,不能在源文件中),而是根据模板定义为它的每个实例生成代码,然后为它的实例编译生成的代码?
(2)。如果我想编写一个提供模板类和模板函数的 C++ 库,是否无法将库编译为共享文件 (.so, .a),因为它们的实例化不会出现在库代码中的任何位置,而只会出现在用户程序?如果是,是否意味着模板库只是源代码文件而不是预编译文件?
C++标准模板库(STL)是如何实现的?其源代码是预编译的还是与用户程序一起编译的?
(3)。在 C 中,
如何编写一个库来提供像 C++ 中的模板函数一样的函数?重载是一个好的解决方案吗?
如果我必须为不同类型的参数编写一个过程到不同的函数中,是否有代码重用的好方法?这是个好方法吗 http://www.vlfeat.org/api/imop_8c_source.html ?还有其他方法吗?
谢谢和问候!
最佳答案
When using C++ template, is it correct that the compiler (e.g. g++) will not compile the template definition.
是的。这是一个正确的假设。
模板定义是不完整的代码。编译前需要填写模板参数。
If I want to write a C++ library which provide template classes and template functions, is it impossible to compile the library into shared file (.so, .a)
不,这不可能。您只能编译模板的单个实例。
How is C++ standard template library (STL) implemented? Is its source code precompiled or compiled together with user's program?
大部分 STL 代码位于头文件中,并与您的应用程序一起编译。
In C, how to write a library that provide functions acting like template functions in C++? Is this a good way to do it http://www.vlfeat.org/api/imop_8c_source.html? Any other ways?
重新定义宏后多次包含同一个文件(如您提供的链接所示)是执行此操作的好方法。
关于c++ - 使用 "template"编写 C 或 C++ 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2348788/