C++——我可以使用一个没有在头文件中实现的模板函数吗

C++ -- Can I use a template function that is not implemented in a header file?

本文关键字:实现 文件 函数 可以使 我可以 C++ 一个      更新时间:2023-10-16

可能重复:
将C++模板函数定义存储在.CPP文件中
为什么模板只能在头文件中实现
为什么模板类的实现和声明应该在同一个头文件中?

我有三个档案。在一个base.h中,我有一个类,它有一个使用模板的成员:

class Base {
    protected:
        template <class T>
            void doStuff(T a, int b);
};

在base.cpp中,我实现了base::doStuff():

#include "base.h"
template <class T>
void Base::doStuff(T a, int b) {
    a = b;
}

然后我试着在我的项目中的另一个类中使用这个:

#include "base.h"
void Derived::doOtherStuff() {
    int c;
    doStuff(3, c);
}

但我收到一个链接错误,说它找不到"doStuff(int,int)"

据我所见,如果不将此函数的实现移动到头文件中,这在C++03中是不可能的。有干净的方法吗?(我对使用C++11x功能很满意)。

将模板定义与内联函数定义一起放入.inl文件中,并将其包含在.h文件的末尾是一种常见的习惯用法:

base.h

#ifndef BASE_H
#define BASE_H
class Base {
    protected:
        template <typename T>
        void doStuff(T a, int b);
};
#include "base.inl"
#endif

base.inl

template <typename T>
void Base::doStuff(T a, int b) {
    a = b;
}