如何在使用模板时将 CPP 代码编译到库文件中
how to compile cpp code into library file while using template
我现在正在写一个关于某种排序算法的项目,但遇到了一些麻烦。这是我的项目结构。我让它变得简单,可能会节省您的时间
//-------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 中。
相关文章:
- 在Linux for Windows上编译C++代码时出错
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在程序中编写脚本来编写和编译代码
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 在macos上编译代码的未解析符号
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 使用指针编译代码后,.cpp文件将变为随机字符
- VS Express 无法正确编译代码(?
- 如何在Ubuntu中使用Visual Studio代码编译C++代码
- 使用 Android NDK 使用 clang++ 编译C++代码时对"_Unwind_Resume"的未定义引用
- 无法使用两个包装不同下一层的ssl_stream编译代码
- 编译代码时"[Warning] extra tokens at end of"
- 无法编译代码,因为它已在 C++11 中弃用
- 如何在 Azure 应用服务中使用 cl.exe 编译 C++ 代码并生成可执行文件
- 如何调试编译 c++ 代码的 bazel?
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 编译 C++ 代码后尺寸较大
- 使用用 C++ 和 DDS 编写的 CMAKE 编译代码
- 编译代码时如何不制作二进制文件?
- 如何使用所有其他文件信息来编译代码,例如HAAR级联训练的权重的XML文件