C++ 模板在 .h 中声明,在 .hpp 中定义

2021-12-13 00:00:00 header templates c++

我看到一些代码,其中开发人员在 .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
}

相关文章