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 中定义
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
