c++ - 使用 "template"编写 C 或 C++ 库

标签 c++ c templates

(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/

相关文章:

c - 该程序的预期输出是什么?

c - 包括静态库和头文件Makefile问题(C)

我可以在 C 程序中使用 cstdio 吗?

c++ - 专用版本是否可以与原始模板类共享某些功能?

c++ - 每当在 C++ 中调用函数时生成新类型

c++ - SetWindowsHookEx 回调函数不适用于 SYSTEM 权限

c++ - 从两个接口(interface)实现创建实例

c++ - 为什么实例化模板类时编译器无法访问 .cpp

C++ 总是在构造函数中使用 Const 引用?

c++ - 具有智能指针的虚拟构造函数习语