c++ - 使用模板时 Unresolved external 问题

标签 c++ templates unresolved-external

我将运算符重新定义与模板类混合在一起,并完成了以下任务:

j = end - begin;

在我的main函数中,变量类型如下:

ptrdiff_t j;
util::BaseArrayIterator<int, 6> begin, end;

开始和结束已从 util::BaseArray 初始化:

util::BaseArray<int, 6> ba(SOME_PARAMETERS);
begin = ba.begin(); end = ba.end();

BaseArrayIterator 是一种自行实现的迭代器类型。

我得到错误:

TestProject.obj : error LNK2019: unresolved external symbol
"int __cdecl util::operator-(class util::BaseArrayIterator<int,6>
const &,class util::BaseArrayIterator<int,6> const &)" 
(??Gutil@@YAHABV?$BaseArrayIterator@H$05@0@0@Z) referenced in
function _main

由于消息中的第一个代码语句(删除它可以解决问题)。

我包含了一个包含以下定义和声明的头文件:

namespace util {
template<typename T, int n>
typename BaseArrayIterator<T,n>::difference_type operator -
    (const BaseArrayIterator<T,n> &itL,
     const BaseArrayIterator<T,n> &itR);
...
template<typename T, int n>
typename BaseArrayIterator<T,n>::difference_type operator -(
    const BaseArrayIterator<T,n> &itL, 
    const BaseArrayIterator<T,n> &itR)
{   return -(itL.m_cnt - itR.m_cnt);
}
}

是什么导致了这个问题? 编译器报告正在搜索 util::operator -,所以他确实找到了声明,但没有找到定义,尽管它们在同一个文件中。而且我没有看到签名错误。

--- 编辑说明---------------------------------------- ------------------------------------

替换

end-begin

util::operator-<int, 6>(end,begin)

解决了问题,但我不想每次都显式指定参数。简洁是支持重载运算符的主要论据之一,因此我想使用经典的简短形式。

--- 编辑注释 2 -------------------------------------- ----------------------------------

正如 Nicola Mussatti 亲切指出的那样,[解决方案]:Unresolved external symbol with operator overloading and templates问题就在这里。友元声明应该移到类中。

所以我做到了,我满脸笑容。 现在再次将它们分开会导致模棱两可的过载问题,这与之前的错误不同。

最佳答案

您使用的是哪个编译器?

VS2010 对这段代码很满意:

namespace util
{
    template<typename T>
    class BaseArrayIterator
    {
    public:
        typedef ptrdiff_t difference_type;

        int pos;
        T x;
    };

    template<typename T>
    typename BaseArrayIterator<T>::difference_type operator -
        (const BaseArrayIterator<T> &itL,
         const BaseArrayIterator<T> &itR);

    template<typename T>
    typename BaseArrayIterator<T>::difference_type operator -
        (const BaseArrayIterator<T> &itL,
         const BaseArrayIterator<T> &itR)
    {
        return itL.pos - itR.pos;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    util::BaseArrayIterator<int> a;
    util::BaseArrayIterator<int> b;

    ptrdiff_t dist = a - b;
    return 0;
}

关于c++ - 使用模板时 Unresolved external 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974011/

相关文章:

c++ - 从 cpp 文件内联函数时出现链接器错误

c++ - "template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };"是什么意思,它如何与 std::visit 一起使用?

javascript - 使用 Handlebars.js 的递归布局

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 收缩 std::vector 's size to fit its actual data to save memory usage? vec.swap() doesn' t 在 MSVC 中工作吗?

c++ - 将 "stored"可变参数模板类型解压到模板参数中

c++ - VS2010 中的 Magick++ - 未解析的外部符号

c++ - std::array 的默认初始化?

C++: 错误: ‘class’ 没有名为的成员

c++ - 线程处理不同类时,条件变量、互斥量应该在哪里声明?