模板类和自由函数名称空间的实现问题 [英] template class and free function namespace problems with implementation

查看:57
本文介绍了模板类和自由函数名称空间的实现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class defined like this (trivial includes and preprocessor wrappers, etc. are omitted, but they are there):

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);

但是,当我这样编译和链接时:

However, when I compile and link like this:

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

我得到一个未定义的参考错误,

I get an undefined reference error, specifically

/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

为什么会出现此错误?在我看来,我的命名空间解析还可以,而且我的链接很好...

Why am I getting this error? It seems to me that my namespace resolution is okay and my linkage is fine...

推荐答案

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

bitExpand defines a free function in global namespace, not in matrixmanip namespace. using directive does not move definitions into the namespace being used. You should put definition in proper namespace directly:

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

这篇关于模板类和自由函数名称空间的实现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆