如何在使用模板时将 CPP 代码编译到库文件中

how to compile cpp code into library file while using template

本文关键字:编译 代码 CPP 文件      更新时间:2023-10-16

我现在正在写一个关于某种排序算法的项目,但遇到了一些麻烦。这是我的项目结构。我让它变得简单,可能会节省您的时间

//-------Sort.h------

#ifndef....
class Sort{
public:
template <typename T>
static bool foo(T* t_, ...);   //maybe more parameters
...                            //and maybe more functions
}
#endif

//--------foo.cpp-----

#include "Sort.h"
template<typename T>
bool Sort::foo(T* t_, ...){
...                             //function implementation
return true;
}
template bool Sort::foo<int>(int*, ...);
template bool Sort::foo<char>(int*, ...);

但是,我发现它不是那么好。我必须在每个.cpp文件的末尾使用特定的模板功能。更重要的是,我不能将这些函数与自定义类一起使用(因为我没有将函数与此类相关联(。

但是如果我将所有内容都写在 Sort.hpp 文件中,我无法将 .hpp 文件编译为 .a 或 .lib。 我可以做些什么来将我的项目编译为库文件,同时减少重复工作?

非常感谢您的帮助。

谢谢

模板必须在头文件中声明。这就是他们的工作方式。不会编译头文件,因为使用库的任何代码中的#include指令都需要它们。Boost 是如何组织模板库的一个很好的例子。

将实现与声明分开是否有效并不总是很清楚。我试图始终将类的标头和 cpp 文件分开,但我经常遇到链接错误,并且根据编译器(或我猜的 IDE(,错误消息可能会有所不同,这令人沮丧。为避免这种情况,只需在头文件中混合实现即可。例

头文件

...   
template<typename T>
class Array
{
public:
~Array() { if (elems != nullptr) delete[] elems; }
Array() : logical_len(0), allocated_len(4), elems(new T[4]) {}
Array(std::initializer_list<T> lst) : logical_len(0),
allocated_len(lst.size() * 2), elems(nullptr) {
elems = new T[allocated_len];
for (const T& x : lst)
push_back(x);
}
...

此时,您有两种选择。您可以将头文件编译为 cpp 文件,也可以只将其 #include 在 main.cpp 中。