gex*_*ide 2 c++ templates include
假设我有一个带有方法模板的类:
//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;
}
Run Code Online (Sandbox Code Playgroud)
由于循环类依赖(foo的主体依赖于Y和Y依赖于X),我无法定义foo我声明它的方法模板(请不要现在质疑设计).
那么,foo在这种情况下把定义放在哪里?我无法将其他定义放入.cpp文件中,否则链接将失败.
我的解决方案是创建一个新的头文件,例如"X.hpp",只添加模板方法的定义.在这个文件中,我包含"Xh"和"Yh".现在,每当我需要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
Run Code Online (Sandbox Code Playgroud)
不需要额外的文件.
| 归档时间: |
|
| 查看次数: |
225 次 |
| 最近记录: |