5

可能重复:
将 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 功能)。

4

1 回答 1

4

Its a common idiom to place template definitions into an .inl file along with inline function definitions, and include it at the end of .h file:

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;
}
于 2012-07-26T20:11:39.007 回答