C++ templates declare in .h, define in .hpp(C++ 模板在 .h 中声明,在 .hpp 中定义)
问题描述
我看到一些代码,其中开发人员在 .h 文件中定义了类模板,并在 .hpp 文件中定义了其方法.这让我有点意外.
I saw some code in which the developer defined a class template in a .h file, and defined its methods in a .hpp file. This caught me a bit by surprise.
在处理模板以及模板应该放在哪些文件中时,C++ 中是否有特定的约定?
Are there are particular conventions in C++ when dealing with templates and what files they should be in?
例如,假设我有一个 Vector 类模板,其中包含用于向量运算(加、减、点等)的方法.如果模板参数是 float(比较运算符),我还想专门化某些函数.您将如何在文件之间分离所有这些(指定是 .h、.hpp、.cpp).
For example say I had a Vector class template with methods for vector operations (add, subtract, dot, etc.). I would also want to specialize certain functions if the template argument is a float (comparison operators). How would you separate all of this between files (specify whether .h, .hpp, .cpp).
推荐答案
通常(根据我的经验,YMMV)hpp 文件是一个 #include-ed CPP 文件.这样做是为了将代码分成两个物理文件,一个主要的包含文件和一个您的库的用户不需要知道的实现细节文件.它是这样完成的:
Typically (in my experience, YMMV) an hpp file is an #include-ed CPP file. This is done in order to break the code up in to two physical files, a primary include and an implementation-details file that the users of your library don't need to know about. It is done like this:
template<...> class MyGizmo
{
public:
void my_fancy_function();
};
#include "super_lib_implementation.hpp"
super_lib_implementation.hpp(您的客户不直接#include)
template<...> void MyGizmo<...>::my_fancy_function()
{
// magic happens
}
这篇关于C++ 模板在 .h 中声明,在 .hpp 中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 模板在 .h 中声明,在 .hpp 中定义
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- C++ 协变模板 2021-01-01
