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

标签 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;
    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/

相关文章:

c++ - 与模板方法不一致的字符串排序

c# - VS2005代码分析: CA1063 (call dispose(true) and supress finalize) - with logging

c - 具有以下要求的适用于 Windows 的简单 2D 图形 C 库?

C# 解析区域日期时间字符串

c++ - 将图像位发送到嵌入在 FPGA 中的 HDL 生成的 RAM block

C++,如何将多个输入除以空格?

c++ - Visual Studio 自动将括号添加到函数名称

c++ - 调用实例化函数期间链接器错误

c++ - 初始化模板 2D std :array to 0 的最快方法

c++ - 为什么我不能在 Windows 上使用 boost::locale::conv::between 将 UTF-16 文本转换为其他编码