C ++仅标头模板库

问题描述:

查看该项目(http://www.savarese.com/software/libssrckdtree/),我发现了仅C ++标头模板库"的定义.目前,我具有基本的C ++知识,但想知道这到底意味着什么,以及为什么这个人在此项目中使用它

Looking at this project (http://www.savarese.com/software/libssrckdtree/) I found the definition "C++ header-only template library". At the moment I have basic C++ knowledge but would like to know what this exactly means and why this people use it on this project

这意味着模板(功能模板或类模板)的所有定义仅在标头中.没有.cpp文件.只有.h个文件(或某些其他扩展名,例如.hpp或根本没有扩展名,例如<vector>string>等)

It means all the definitions of template (function template or class template) are in the headers only. There is no .cpp file. There are only .h files (or some other extensions such as .hpp or no extension at all like <vector>, string> etc)

C ++编译器要求模板的定义必须存在于声明它们的同一文件中.因此,仅标头库既不是静态库也不是动态库.它的 source-code 库意味着您可以在标题中看到实现.您已经在代码中包含了头文件,这些头文件与库中的头文件一起被编译.

C++ compilers require the definitions of templates to be present in the same file in which they're declared. As such, the header-only library is neither static library or dynamic library. Its source-code library which means you can see the implementation in the headers. You've include the header files in your code, which gets compiled along with the headers from the library.

请注意,使用诸如<vector>string><map>等模板的C ++标准库部分是仅标头的库.

Note the part of the C++ Standard Library which makes use of templates such as <vector>, string>, <map>, etc is header-only library.

实际上,模板(类模板和功能模板)无法编译为静态或动态库以链接到程序.顾名思义,模板就是一个模板.这不是正常的代码;仅当您在传递模板参数(为typevalue)的代码中使用它时,编译器才会从函数/类模板中生成可编译的函数/类:

Actually templates (class templates and function templates) cannot be compiled into static or dynamic library to be linked to programs. A template is, as the term itself says, a template; it's not normal code; its only when you use it in your code passing template argument(s) (which is either type or value), the compiler generates a compilable function/class out of the function/class template:

template<typename T>
struct A
{
   T data;
};

struct B
{
   int data;
};

在这里,A无法编译为二进制文件(静态库或动态库),因为编译器不知道T是什么.但是B可以编译为二进制文件,因为编译器具有完整的信息.

Here, A cannot be compiled into binary (static library or dynamic library), because the compiler doesn't know what T is. But B can be compiled into binary, as the compiler has complete information about it.

因此,您可以阅读短语类模板A" ,因为:A是类的模板. A本身不是类.但是B是一个类,不是模板.

So you can read the phrase "class template A" as : A is a template for a class. A itself is not a class. But B is a class, its not a template.

由于类模板A无法编译为静态或动态库以链接到您的程序,因此A只能作为具有完整源代码的header-only库提供.同样

As the class template A cannot be compiled into static or dynamic library to be linked to your programs, so A can be shipped only as header-only library with full source code. Likewise