5

Possible Duplicate:
Storing C++ template function definitions in a .CPP file
Why can templates only be implemented in the header file?
Why should the implementation and the declaration of a template class be in the same header file?

I have three files. In one, base.h, I have a class that has a member utilizing a template:

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

In base.cpp, I implement Base::doStuff():

#include "base.h"

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

I then try to use this in another class in my project:

#include "base.h"

void Derived::doOtherStuff() {
    int c;
    doStuff(3, c);
}

But I get a linking error that states that it can't find 'doStuff(int, int)'

From what I've seen, this is not possible in C++03 without moving the implementation of this function into the header file. Is there a clean way to do this? (I'm fine with using C++11x features).

Community
  • 1
  • 1
crosstalk
  • 328
  • 6
  • 12
  • A template is exactly that what its named: a template for a function. Therefor `doStuff` is something different than `doStuff`. It will generate 2 functions one for `int` types and one for `char` types. Since its not a function you cant prototype it. This is the simple answere. – Sebastian Hoffmann Jul 26 '12 at 20:11
  • You can add `template void Base::doStuff (int a, int b);` to your `.cpp` file to explicitly instantiate the template for an `int` parameter. – jxh Jul 26 '12 at 20:19

1 Answers1

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;
}
yuri kilochek
  • 12,709
  • 2
  • 32
  • 59
  • Ah, that makes sense. I do that unless I somehow get a better response. – crosstalk Jul 26 '12 at 20:15
  • this does not solve an issue where the implementation uses some dependant header. export templates was part of standard and had implementations. hoping to see it next standard after 20 – Sergei Krivonos Dec 25 '19 at 12:03