模板 class 和自由函数命名空间的实现问题

template class and free function namespace problems with implementation

我有一个这样定义的 class(省略了琐碎的包含和预处理器包装器等,但它们在那里):

In Matrix.h

namespace matrixmanip {
template<typename T>
class Matrix {
    public:
        void someFunc() const;
    //...
};

template<typename T>
void Matrix<T>::someFunc() const {
    //...
}
} // namespace matrixmanip

In bitTransform.h

#include "Matrix.h"

namespace matrixmanip {
Matrix<char> bitExpand(const Matrix<char> &mat);
} // namespace matrixmanip

In bitTransform.cpp

#include "bitTransform.h"

using namespace matrixmanip;

Matrix<char> bitExpand(const Matrix<char> &mat) {
    mat.someFunc();
    //...
}

In tester.cpp

#include "Matrix.h"
#include "bitTransform.h"

matrixmanip::Matrix<char> A ... // construct a character matrix, details of which are unimportant here
matrixmanip::Matrix<char> B = matrixmanip::bitExpand(A);

然而,当我像这样link编译时:

g++ -c tester.cpp
g++ -c bitTransform.cpp
g++ -Wall -O2 tester.o bitTransform.o -o tester

我得到一个未定义的引用错误,特别是

/tmp/ccateMEK.o: In function `main':
tester.cpp:(.text+0xbf9): undefined reference to `matrixmanip::bitExpand(matrixmanip::Matrix<char> const&)'
collect2: error: ld returned 1 exit status

为什么会出现此错误?在我看来,我的名称空间解析没问题,我的 linkage 也很好...

bitExpand 在全局命名空间中定义了一个自由函数,而不是在 matrixmanip 命名空间中。 using 指令不会将定义移动到正在使用的名称空间中。您应该直接将定义放在适当的命名空间中:

namespace matrixmanip
{
    Matrix<char> bitExpand(const Matrix<char> &mat)
    {
        mat.someFunc();
       //...
    }
}