下面的代码重现了我在 VS2005 中遇到的一个错误:我有一个像这样的模板函数
template <typename T> bool foo(T x, T y) {
struct bar {
public:
T t;
bool CompLT(const bar& that) {
return (this->t) < (that.t);
}
};
bar X, Y;
X.t = x;
Y.t = y;
return X.CompLT(Y);
}
在头文件 A.h 中。当我现在在两个编译单元 B.cpp 和 C.cpp 中使用 header 时,VS2005 会报错
error LNK2005: "public: bool __thiscall `bool __cdecl foo<float>(float,float)'::`2'::bar::CompLT(struct `bool __cdecl foo<float>(float,float)'::`2'::bar const &)" (?CompLT@bar@?1???$foo@M@@YA_NMM@Z@QAE_NABU1?1???$foo@M@@YA_NMM@Z@@Z) is already defined in B.obj .
如何解决这个错误?这是 VS2005 的问题还是我必须将结构的定义移出局部函数范围并使其成为模板?
最佳答案
关于c++ - 模板函数中的局部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19426297/