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 中定义


基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01