本文介绍了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 (比较运算符),我还希望专门化某些函数。

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).

推荐答案

通常情况下(在.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



super_lib_implementation.hpp (your clients do not #include this directly)

template<...> void MyGizmo<...>::my_fancy_function()
{
 // magic happens
}

这篇关于C ++模板在.h中声明,在.hpp中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:02