且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对模板函数的未定义引用

更新时间:2023-10-25 14:09:52

非专用模板的实现必须对使用它的翻译单元可见.

The implementation of a non-specialized template must be visible to a translation unit that uses it.

编译器必须能够看到实现,才能为代码中的所有特化生成代码.

The compiler must be able to see the implementation in order to generate code for all specializations in your code.

这可以通过两种方式实现:

This can be achieved in two ways:

1) 将实现移到标题内.

1) Move the implementation inside the header.

2) 如果您想将其分开,请将其移动到包含在原始标题中的不同标题中:

2) If you want to keep it separate, move it into a different header which you include in your original header:

util.h

namespace Util
{
    template<class T>
    QString convert2QString(T type , int digits=0);
}
#include "util_impl.h"

util_impl.h

namespace Util
{
    template<class T>
        QString convert2QString(T type, int digits=0)
        {
            using std::string;

            string temp = (boost::format("%1") % type).str();

            return QString::fromStdString(temp);
        }
}