C++模板依赖关系

C++ template dependencies

本文关键字:关系 依赖 C++      更新时间:2023-10-16

我有一个关于c++中模板的循环依赖关系的问题。我有两个模板类,Rotation3和Vector3。旋转保持水平和垂直旋转,而向量具有x、y和z分量。

我希望每个类都有一个用于另一个类的构造函数:

Vector3<T>::Vector3(const Rotation3<T>& rot)

而且。。。

Vector3<T>::Rotation3(const Vector3<T>& vec)

但是,由于模板不能放在.cpp文件中,并且必须放在.h中,这意味着Vector3.h和Rotation3.h都必须包含彼此,才能将彼此用于其构造函数。这可能吗?

感谢您的提前帮助,我对c++还很陌生,我真的很想知道有经验的人会如何设计这个。

使用不在文件开头但有效的#include指令会有点奇怪。包括在内的警卫比平时更重要。

// Vector3.hpp
#ifndef VECTOR3_HPP_
#define VECTOR3_HPP_
template<typename T> class Rotation3;
template<typename T> class Vector3
{
public:
    explicit Vector3(const Rotation3<T>&);
};
#include "Rotation3.hpp"
template<typename T>
Vector3<T>::Vector3(const Rotation3<T>& r)
{ /*...*/ }
#endif
// Rotation3.hpp
#ifndef ROTATION3_HPP_
#define ROTATION3_HPP_
template<typename T> class Vector3;
template<typename T> class Rotation3
{
public:
    explicit Rotation3(const Vector3<T>&);
};
#include "Vector.hpp"
template<typename T>
Rotation3<T>::Rotation3(const Vector3<T>& v)
{ /*...*/ }
#endif

如果Vector3和Rotatio3都是Templates,则不会发生任何事情,因为模板在被专门化或使用之前不会生成对象(例如Vector3)。

您可以通过组合或继承创建另一个同时包含vector3和Rotation3的类,并根据需要使用它们。这也可以是一个模板(模板Vector3,模板Rotation3>示例)

像往常一样,您可以只声明一些东西,并且该声明可能足够好。模板的声明与其他模板类似,只是省略了定义部分。

模板类成员函数也可以在类之外定义。您可以将头拆分为只定义类和另一个实现函数。然后你可以把它们交错放进去。