假设我有一个带有方法模板的类:
//file: X.h
class X{
int x;
//... more members and non-template functions
template<typename T>
void foo(T t){ //Error, cannot define the method here. Declaration is okay
Y y = ...;
}
}
//file Y.h
class Y {
X x;
}
由于循环类依赖(foo 的主体依赖于 Y,Y 依赖于 X),我无法定义声明它的方法模板 foo
(请现在不要质疑设计) .
那么,在这种情况下,将 foo
的定义放在哪里呢?我无法将其放入 .cpp 文件中的其他定义,否则链接将失败。
我的解决方案是创建一个新的头文件,例如“X.hpp”,只将模板方法的定义添加到其中。在此文件中,我包括“X.h”和“Y.h”。现在,每当我需要 X 类时,我只需仅包含“X.hpp”,它将依次包含其他必要的 h 文件。
所以我的问题是:这是正确/最好的方法吗?不知何故,我有一个仅用于单个方法模板定义的 .hpp 文件,但这似乎是在循环类型依赖项的情况下唯一可能的方法。再次请注意:不要通过说“最好避免循环类型依赖”或类似的话来质疑设计。问题是:如果我有这些依赖项,处理单一方法模板的最佳方法是什么。
最佳答案
不质疑设计:
//file: X.h
#ifndef X_H
#define X_H
class X{
int x;
//... more members and non-template functions
template<typename T>
void foo(T t);
};
#include "Y.h"
template<typename T>
void X::foo(T t){ //Error, cannot define the method here. Declaration is okay
Y y = ...;
}
#endif
//file Y.h
#ifndef Y_H
#define Y_H
#ifndef X_H
#error "Please include X.h"
#endif
class Y {
X x;
}
#endif
不需要额外的文件。
关于C++:非内联模板方法的放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12142292/