gpt4 book ai didi

c++ - 模板函数中的局部结构

转载 作者:太空狗 更新时间:2023-10-29 23:17:12 26 4
gpt4 key购买 nike

下面的代码重现了我在 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.cppC.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 的问题还是我必须将结构的定义移出局部函数范围并使其成为模板?

最佳答案

你用过include guards吗? ?

尝试添加以下内容并删除任何目标文件(以 .o 结尾)

#ifndef A_H
#define A_H

//your header

#endif

关于c++ - 模板函数中的局部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19426297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com