C++ 模板函数中的局部结构
下面的代码复制了我在VS2005中得到的一个错误:我有一个模板函数,如C++ 模板函数中的局部结构,c++,templates,visual-studio-2005,C++,Templates,Visual Studio 2005,下面的代码复制了我在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;
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);
}
模板bool foo(tx,ty){
结构条{
公众:
T;
bool CompLT(const bar&that){
返回(this->t)<(that.t);
}
};
条X,Y;
X.t=X;
Y.t=Y;
返回X.CompLT(Y);
}
在头文件a.h.中,当我现在在两个编译单元B.cpp和C.cpp 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 .
错误LNK2005:“public:bool\uu thiscall`bool\uu cdecl foo(float,float):`2'::bar::CompLT(struct`bool\uu cdecl foo(float,float):`2'::bar const&”)”(?CompLT@bar@?1???$foo@M@@嗯_NMM@Z@QAE_NABU1?1$foo@M@@嗯_NMM@Z@@Z) 已在B.obj中定义。
如何修复此错误?这是VS2005的问题吗?还是我必须将结构的定义移出本地函数范围并使其成为模板?您使用过吗
尝试添加以下内容并删除任何对象文件(以.o结尾)
从评论中可以清楚地看出,这是VS2005中的一个bug。由于没有人能够提供一些关于问题确切来源的见解,因此我将给出我的解决方案:我将函数移到一个静态模板类中,并将内部结构定义为该类模板中的私有局部结构。您是否有a.h中的#pragma?您可以尝试将
CompLT
标记为inline
(即使这应该是自动的)。和/或将foo
标记为inline
。这听起来像是编译器的问题。您是否在新的Visual Studio或GCC中尝试过这一点?无法重现我所期望的错误。我听说VS2005没有那么令人高兴的地方…在VS 2012和2013上编译得很好。结论:停止使用史前工具。这个问题根本不相关d到多个定义。
#ifndef A_H
#define A_H
//your header
#endif