G++ 模板实例化导致 "Undefined reference to" 错误

G++ Template instantiation results in "Undefined reference to" error

我最近在使用自定义编写的通用矢量代码时遇到了一些问题,这些代码依赖于功能模板。我不愿意将实现包含在头文件中(这在模板中很常见),因为这会显着增加编译时间。因此,我改为在 .cpp 文件中手动实例化所需的 class 。但是,这仍然会导致未定义的引用错误。我已将代码缩减为以下片段,它仍然会产生错误:

matrixd.cpp

#include "matrixd.h"

namespace math
{
    template class _vec2<float>;
    template<class T> _vec2<T>::_vec2() {}
}

matrixd.h

#pragma once
namespace math
{ 
    template <class T>
    class _vec2
    {
    public:
        T x, y;
        _vec2<T>();
        void reset();
    };

    typedef _vec2<float> vec2;
}

test.cpp

#include "matrixd.h"

int main()
{
    math::_vec2<float> v;
}

错误信息:

In function main': source.cpp:(.text+0x10): undefined reference to math::_vec2::_vec2()' collect2: error: ld returned 1 exit status

如有任何帮助,我们将不胜感激! :)

显式实例化定义(template class _vec2<float>; 在您的代码中)仅实例化在显式实例化时定义的成员函数。 _vec2<T>::_vec2() 是在显式实例化定义之后定义的,因此没有显式实例化。

解决方法是交换两行:

namespace math
{
    template<class T> _vec2<T>::_vec2() {}
    template class _vec2<float>;
}